Reputation: 93
I have been trying for hours using Google and stack overflow to read a list of IP addresses and return networks. The ip address command works in the Python shell but seems to be tripping over the imported list. I have tried stripping the new line and reading the file in multiple different ways but I keep getting an error returned. I am sure it is something with how I am reading the file in but I just can't figure it out.
Here is the current code. Let's call it revision number 4186!
import ipaddress
def process(line):
# Output network with mask bits (192.168.0.0/24)
try:
return ipaddress.IPv4Interface(line).network
except Exception:
return print("FAIL_OR_EMPTY")
with open('ipaddrlong.txt', 'r') as f:
for line in f:
process(line)
and the input file called looks like this. There is only the data and a newline (/n).
192.168.252.146/24
192.168.252.158/24
192.168.252.203/24
192.168.252.209/24
If I change the return line to a simple print, it looks fine to me.
'192.168.252.146/24', '192.168.252.158/24', '192.168.252.203/24', '192.168.252.209/24'
And when I try the command from the shell, it seems to work fine:
>>> x="192.168.0.1/24"
>>> ipaddress.IPv4Interface(x).network
IPv4Network('192.168.0.0/24')
But when I run the script the exception "FAIL_OR_EMPTY" is returned.
Upvotes: 0
Views: 934
Reputation: 413
As far as I can tell you have a problem with white-spaces after your IP-adresses, which you have to strip off the string first with something like this:
import ipaddress
def process(line):
# Output network with mask bits (192.168.0.0/24)
try:
return print(ipaddress.IPv4Interface(line).network)
except Exception:
return print("FAIL_OR_EMPTY")
with open('in.txt', 'r') as f:
for line in f:
line = "".join(line.split())
process(line)
My in.txt looks like this
192.168.252.146/24
192.168.252.158/24
192.168.252.203/24
192.168.252.209/24
I'm not an IP adr
192.168.252.209/24
Output
192.168.252.0/24
192.168.252.0/24
192.168.252.0/24
192.168.252.0/24
FAIL_OR_EMPTY
192.168.252.0/24
Upvotes: 1