Oleksandr Savatieiev | fb9f943 | 2018-11-23 17:39:12 +0100 | [diff] [blame] | 1 | import re |
| 2 | import sys |
| 3 | import subprocess |
| 4 | import json |
| 5 | |
| 6 | |
| 7 | def shell(command): |
| 8 | _ps = subprocess.Popen( |
| 9 | command.split(), |
| 10 | stdout=subprocess.PIPE |
| 11 | ).communicate()[0].decode() |
| 12 | |
| 13 | return _ps |
| 14 | |
| 15 | |
| 16 | def cut_option(_param, _options_list): |
| 17 | _option = "n/a" |
| 18 | _result_list = [] |
| 19 | if _param in _options_list: |
| 20 | _index = _options_list.index(_param) |
| 21 | _option = _options_list[_index+1] |
| 22 | _l1 = _options_list[:_index] |
| 23 | _l2 = _options_list[_index+2:] |
| 24 | _result_list = _l1 + _l2 |
| 25 | else: |
| 26 | _result_list = _options_list |
| 27 | return _option, _result_list |
| 28 | |
| 29 | |
| 30 | def get_ifs_data(): |
| 31 | _ifs_raw = shell('ip a') |
| 32 | |
| 33 | if_start = re.compile("^[0-9]+: .*: \<.*\> .*$") |
| 34 | if_ipv4 = re.compile("^\s{4}inet\ .*$") |
| 35 | |
| 36 | _ifs = {} |
| 37 | _if_name = None |
| 38 | for line in _ifs_raw.splitlines(): |
| 39 | _if_data = {} |
| 40 | if if_start.match(line): |
| 41 | _tmp = line.split(':') |
| 42 | _if_name = _tmp[1].strip() |
| 43 | _if_options = _tmp[2].strip().split(' ') |
| 44 | _if_data['order'] = _tmp[0] |
| 45 | _if_data['mtu'], _if_options = cut_option("mtu", _if_options) |
| 46 | _if_data['qlen'], _if_options = cut_option("qlen", _if_options) |
| 47 | _if_data['state'], _if_options = cut_option("state", _if_options) |
| 48 | _if_data['other'] = _if_options |
| 49 | _if_data['ipv4'] = {} |
| 50 | _ifs[_if_name] = _if_data |
| 51 | elif if_ipv4.match(line): |
| 52 | if _if_name is None: |
| 53 | continue |
| 54 | else: |
| 55 | _tmp = line.strip().split(' ', 2) |
| 56 | _ip = _tmp[1] |
| 57 | _options = _tmp[2].split(' ') |
| 58 | _brd, _options = cut_option("brd", _options) |
| 59 | # TODO: Parse other options, mask, brd, etc... |
| 60 | _ifs[_if_name]['ipv4'][_ip] = {} |
| 61 | _ifs[_if_name]['ipv4'][_ip]['brd'] = _brd |
| 62 | _ifs[_if_name]['ipv4'][_ip]['other'] = _options |
| 63 | |
| 64 | return _ifs |
| 65 | |
| 66 | |
| 67 | ifs_data = get_ifs_data() |
| 68 | |
| 69 | # _ifs = sorted(ifs_data.keys()) |
| 70 | # _ifs.remove("lo") |
| 71 | # for _idx in range(len(_ifs)): |
Alex Savatieiev | d48994d | 2018-12-13 12:13:00 +0100 | [diff] [blame] | 72 | # print("\t{}:\t{},\t\t{},\t{}".format( |
Oleksandr Savatieiev | fb9f943 | 2018-11-23 17:39:12 +0100 | [diff] [blame] | 73 | # _ifs[_idx], |
| 74 | # " ".join(ifs_data[_ifs[_idx]]['ipv4'].keys()), |
| 75 | # ifs_data[_ifs[_idx]]['mtu'], |
| 76 | # ifs_data[_ifs[_idx]]['state'] |
| 77 | # )) |
| 78 | |
| 79 | |
| 80 | buff = json.dumps(ifs_data) |
| 81 | sys.stdout.write(buff) |