Skip to content

Instantly share code, notes, and snippets.

@cdecl
Last active May 11, 2021 01:40
Show Gist options
  • Save cdecl/145797ab05b36079ccb33f3a9c2cae0c to your computer and use it in GitHub Desktop.
Save cdecl/145797ab05b36079ccb33f3a9c2cae0c to your computer and use it in GitHub Desktop.
import sys
import re
import json
# get description
def get_desc(line):
desc = {}
reg = re.compile(r'([\w]+[ \n]+)')
mat = reg.findall(line)
for m in mat:
desc[m.strip()] = len(m)
if '\n' in m: desc[m.strip()] = 100
return desc
# interfrace status
def if_status(desc, line):
row = {}
for x in desc.keys():
sz = desc[x]
row[x] = line[0:sz].strip()
line = line[sz:]
# print(line)
return row
# mac addr dictionary
def mac_addr(path):
reg = re.compile(r'([\w]{4}\.[\w]{4}\.[\w]{4})[ ]+([\w]+)[ ]+([\w/]+)')
dict = {}
with open('{}/show mac address-table.txt'.format(path), 'r') as f:
while True:
line = f.readline()
if not line: break
r = reg.findall(line)
if len(r) > 0:
r = r[0]
dict[r[2]] = [r[0], r[1]]
return dict
# interfrace status
def port_list(path, dict):
ports = []
desc = {}
with open('{}/show interfaces status.txt'.format(path), 'r') as f:
while True:
line = f.readline()
if not line: break
if 'Port' in line:
desc = get_desc(line)
break
while True:
line = f.readline()
if not line: break
row = if_status(desc, line)
row['Mac'] = ''
row['Type'] = ''
if row['Port'] in dict:
row['Mac'] = dict[row['Port']][0]
row['Type'] = dict[row['Port']][1]
ports.append(row)
return ports
def main():
if len(sys.argv) != 2:
# print('Error: needs to switch log path')
exit(-1)
path = sys.argv[1]
dict = {}
try:
dict = mac_addr(path)
except Exception as e:
exit(-1)
ports = port_list(path, dict)
output = { path.replace(' ', ''): ports }
# print(output)
print(json.dumps(output))
if __name__ == '__main__':
main()
# find . -name 'show mac address-table.txt' | xargs -n1 -i dirname {} | xargs -n1 -i python3 port.py {} > port.json
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment