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


i new in python. scan ip-addresses in python , want read file ip-addresses in different notation cidr or ranges , script should extract ip cidr/ranges individual ip-addresses.

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

any idea how? or tool use that?

i think you'll find python-iptools package you're looking for. so:

with open("test.txt", "r") file_in:     ips_and_ranges = iprangelist(file_in.readlines())  open("ip-test2.txt","w") file_out:     ip in ips_and_ranges:         file_out.write(ip) 

assuming file_in reasonable size, otherwise might need read in chunks.

update: initial code needed "splat" unpack list args, , remove newlines (thus, "basically" :p). also, handle ranges "10.1.1.1-255" requires massaging of data; iptools supports taking ranges tuple. assuming ranges occur in last octet, 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  open("test.txt", "r") file_in:     in_list = [clean(x) x in file_in.readlines()]  ips_and_ranges = iprangelist(*in_list)  open("ip-test2.txt", "w") file_out:     ip in ips_and_ranges:         file_out.write(ip) 

Comments

Popular posts from this blog

php - failed to open stream: HTTP request failed! HTTP/1.0 400 Bad Request -

java - How to filter a backspace keyboard input -

java - Show Soft Keyboard when EditText Appears -