I am trying to write a program that runs a command on Cisco router and writes list of IP on a text file. I am able to write all IPs to the file and then grab all IPs successfully. Now the part where I am having trouble is that I do not know how many IPs I will get from the list. As I would like to compare each IP I get from file against user's defined IP, I would like a way to either create dynamic variable based on # of IPs or somehow iterate through all IPs and compare it against user's IP.
import re
import ipaddr
userIP = raw_input('Enter IP address to compare i.e, 10.10.10.0/24:')
ipFile = ("router.com.txt")
found = []
with open(ipFile, 'r') as f:
for text in f.readlines()[1:]: #File had a blank line so this skips it
text = text.rstrip()
regex = re.findall(r'(?:[\d]{1,3})\.(?:[\d]{1,3})\.(?:[\d]{1,3})\.(?:[\d]{1,3})\/(?:[\d]{1,3})', text)
#print regex
found.append(regex)
print found
print len(found) - 1
This is what I get when I run it:
[['10.10.20.192/27'], ['10.10.40.0/24'], []]
2
Now the hard part where I am struggling is how can I compare each of these with variable userIP dynamically.
#if userIP.overlaps(found):
#print "Overlapping IPs!!"
#else:
#print "Does not Overlap!!"
Thanks Damon
ipaddresslibrary if you are using Python 3.3+. However, for Py2.7 there is a backport package you can still use: pypi.python.org/pypi/py2-ipaddress