Created
August 4, 2015 18:54
-
-
Save truekonrads/9b314095425f0555d357 to your computer and use it in GitHub Desktop.
Extract interface IPs from a directory full of fortinet configs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/usr/bin/python | |
| # Extract known ranges from Fortinet configs and present them as CSV | |
| import os,csv,sys,re,ipaddress | |
| csvwriter=csv.DictWriter(sys.stdout,"filename name vdom ip mask cidr".split(" ")) | |
| if len(sys.argv)<2: | |
| print "Usage %s <directory>" % sys.argv[0] | |
| sys.exit(-1) | |
| csvwriter.writeheader() | |
| for root, dirs, files in os.walk(sys.argv[1]): | |
| for f in filter(lambda x: x.endswith(".conf"),files): | |
| data={ | |
| 'filename':f, | |
| 'interfaces':[]} | |
| systemcontext=False | |
| it=file(os.path.join(root,f),"rb").xreadlines() | |
| for l in it: | |
| # print l | |
| m=re.match(r'^\s*set hostname "([^"]+)',l) | |
| if m: | |
| data['hostname']=m.group(1) | |
| continue | |
| if re.match(r'^\s*config system interface',l): | |
| systemcontext=True | |
| continue | |
| if systemcontext: | |
| if re.match(r'^\s*end',l): | |
| break | |
| m=re.match(r'\s*edit "([^"]+)',l) # in int context | |
| if m: | |
| intdesc={'name':m.group(1)} | |
| data['interfaces'].append(intdesc) | |
| continue | |
| m=re.search(r'^\s*set vdom "([^"]+)',l) | |
| if m: | |
| intdesc['vdom']=m.group(1) | |
| continue | |
| # if l.find("set ip")>-1: | |
| # print l | |
| m=re.match(r'^\s*set ip (\S+) (\S+)',l) | |
| if m: | |
| intdesc['ip']=m.group(1) | |
| intdesc['mask']=m.group(2) | |
| intdesc['cidr']=ipaddress.IPv4Network("%s/%s" % (m.group(1),m.group(2)),strict=False) | |
| continue | |
| # print data | |
| for interface in data['interfaces']: | |
| # print interface | |
| if not interface.has_key('ip'): | |
| interface['ip']='' | |
| interface['mask']='' | |
| interface['cidr']='' | |
| if not interface.has_key('vdom'): | |
| interface['vdom']='' | |
| csvwriter.writerow({ | |
| 'filename':data['filename'], | |
| 'name': interface['name'], | |
| 'vdom': interface['vdom'], | |
| 'ip': interface['ip'], | |
| 'mask': interface['mask'], | |
| 'cidr': str(interface['cidr']) | |
| }) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment