Loretta
Loretta

Reputation: 154

python extract ip-addresse cidre/-ranges into individual ip-addresses

I am new in python. I would like to scan ip-addresses in python and for that I want to read a file with ip-addresses in different notation like cidr or ranges and the script should extract the ip cidr/ranges into individual ip-addresses.

file_in = open("test.txt", "r")
file_out = open("ip-test2.txt","w")
i = 1
for line in file_in:
    #take the line and look if that is a individual ip , if not make block of ip-    
addresses and write them into a new file_out
    file_out.write(str(i) + ": " + line)
    i = i + 1
file_out.close()
file_in.close()

Any idea how? or which tool I could use for that?

Upvotes: 1

Views: 1687

Answers (1)

Nathan Hoover
Nathan Hoover

Reputation: 636

I think you'll find that the python-iptools package will do what you're looking for. Basically like so:

with open("test.txt", "r") as file_in:
    ips_and_ranges = IpRangeList(file_in.readlines())

with open("ip-test2.txt","w") as file_out:
    for ip in ips_and_ranges:
        file_out.write(ip)

Assuming that file_in is a reasonable size, otherwise you might need to read it in chunks.

UPDATE: My initial code needed a "splat" to unpack the list into args, and also to remove newlines (thus, "basically" :P). Also, to handle the ranges like "10.1.1.1-255" requires some massaging of the data; iptools supports taking ranges like that as a tuple. Assuming the ranges like that only occur in the last octet, this works:

from iptools import IpRangeList

def clean(ip_string):

    ret = ip_string.strip()
    if "-" in ret:
        parts = ret.split("-")
        ret = (parts[0], ret.rsplit(".", 1)[0] + "." + parts[1])

    return ret

with open("test.txt", "r") as file_in:
    in_list = [clean(x) for x in file_in.readlines()]

ips_and_ranges = IpRangeList(*in_list)

with open("ip-test2.txt", "w") as file_out:
    for ip in ips_and_ranges:
        file_out.write(ip)

Upvotes: 1

Related Questions