Frage

recently , i find the python library "iptools" can help me to solve some problem , but i meet a problem in iptools.IpRangeList , i only can declare the initial data in first , like

internalIP = iptools.IpRangeList(
'127.0.0.1/8',                
'192.168/16',               
'10.0.0.1/8'  

)

if i want to add a new ip into IpRangeList , compiler always show error

internalIP.append('1.1.1.1')
AttributeError: 'IpRangeList' object has no attribute 'append'

or openfrom file

intranetlist = IpRangeList()
if os.path.isfile("/tmp/intranal.list"):
    fp = open("/tmp/intranal.list", 'r')
    intranetlist = ([line.strip() for line in fp])        
    print intranetlist , len(intranetlist)
    fp.close()
    return

Result : ['127.0.0.1/8', '192.168/16', '10.0.0.0/8'] 3

it is incorrect , the correct result is as below

>>> from iptools import *
>>> a=IpRangeList('127.0.0.1/8' , '192.168/16', '10.0.0.0/8')
>>> print a
(('127.0.0.0', '127.255.255.255'), ('192.168.0.0', '192.168.255.255'), ('10.0.0.0', '10.255.255.255'))
>>> len(a)
33619968
>>> 

can anyone help me to solve this problem ? or have other library i can use for ?

Thanks.

War es hilfreich?

Lösung

You are receiving that AttributeError because the IpRangeList object doesn't have an append method defined. Plus, internally it defines the IP listing as a tuple which you can't append to.

What you can do however is create a complete list of the IP ranges you want and then create the IpRangeList from that using *args syntax to unpack the list into the function call, like so:

intranetlist = None
if os.path.isfile("/tmp/internal.list"):
    fp = open("/tmp/internal.list", 'r')
    intranetlist = IpRangeList(*[line.strip() for line in fp])
    print intranetlist , len(intranetlist)
    fp.close()
return intranetlist

As for appending to an already existing IpRangeList, that won't be possible without changing it, nor does it look like you can easily access the list of IPs once you've created an IpRangeList. So I'd suggest creating a basic Python list and creating the IpRangeList at the last possible moment, because they are effectively immutable.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top