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!
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. There are no extra spaces or characters.
'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:
But when I run the script the exception "FAIL_OR_EMPTY" is returned. I tried strip() but since there are no extra spaces, that did not help.
Here is the current code. Let's call it revision number 4186!
1 2 3 4 5 6 7 8 9 10 |
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) |
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. There are no extra spaces or characters.
'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:
1 2 3 |
>>> x = "192.168.0.1/24" >>> ipaddress.IPv4Interface(x).network IPv4Network( '192.168.0.0/24' ) |