I have text that contains IP and subnet data. I need to output each IP within a given range. The input looks like this:
10.14.21.23 0.0.0.0
20.54.0.0 0.0.127.255
30.76.21.0 0.0.0.255
40.24.21.135 0.0.0.0
and the output needs to look like this:
10.14.21.23
20.54.0.1
20.54.0.2
20.54.0.3
20.54.0.4
...
20.54.127.254
30.76.21.1
30.76.21.2
30.76.21.3
30.76.21.4
...
30.76.21.254
40.24.21.135
I have isolated the IPs with:
for line in file.readlines():
if re.findall(r'\d+\.\d+\.\d+\.\d+?', line):
tuples = re.findall(r'\d+\.\d+\.\d+\.\d+', line)
This places the IP and subnet into tuples[0] and tuples[1]. Is this the best way to handle this data? How do you calculate each IP within a given range?
Thanks in advance.
You could use ipcalc:
#!/usr/bin/python
import ipcalc
import sys
for data in sys.argv[1:]:
with open(data) as data:
for data in data:
data = data.split()
# Convert subnet mask to count
data[1] = ipcalc.IP(data[1]).bin().count('0')
data = ipcalc.Network(*data)
data = list(data)
if len(data) == 1:
print data[0]
else:
for data in data[1:-1]:
print data
Ref:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With