Debian Codegraph @

ip/routel

raw
1 #! /usr/bin/env python3
2 # SPDX-License-Identifier: GPL-2.0
3 #
4 # This is simple script to process JSON output from ip route
5 # command and format it. Based on earlier shell script version.
6 """Script to parse ip route output into more readable text."""
7
8 import sys
9 import json
10 import getopt
11 import subprocess
12
13
14 def usage():
15 '''Print usage and exit'''
16 print("Usage: {} [tablenr [raw ip args...]]".format(sys.argv[0]))
17 sys.exit(64)
18
19
20 def main():
21 '''Process the arguments'''
22 family = 'inet'
23 try:
24 opts, args = getopt.getopt(sys.argv[1:], "h46f:", ["help", "family="])
25 except getopt.GetoptError as err:
26 print(err)
27 usage()
28
29 for opt, arg in opts:
30 if opt in ["-h", "--help"]:
31 usage()
32 elif opt == '-6':
33 family = 'inet6'
34 elif opt == "-4":
35 family = 'inet'
36 elif opt in ["-f", "--family"]:
37 family = arg
38 else:
39 assert False, "unhandled option"
40
41 if not args:
42 args = ['0']
43
44 cmd = ['ip', '-f', family, '-j', 'route', 'list', 'table'] + args
45 process = subprocess.Popen(cmd, stdout=subprocess.PIPE)
46 tbl = json.load(process.stdout)
47 if family == 'inet':
48 fmt = '{:15} {:15} {:15} {:8} {:8}{:<16} {}'
49 else:
50 fmt = '{:32} {:32} {:32} {:8} {:8}{:<16} {}'
51
52 # ip route json keys
53 keys = ['dst', 'gateway', 'prefsrc', 'protocol', 'scope', 'dev', 'table']
54 print(fmt.format(*map(lambda x: x.capitalize(), keys)))
55
56 for record in tbl:
57 fields = [record[k] if k in record else '' for k in keys]
58 print(fmt.format(*fields))
59
60
61 if __name__ == "__main__":
62 main()