遍历IP列表地址

问题描述 投票:-1回答:2

我有一个包含不同IP地址范围和不同子网的文件。我现在想获取所有范围的所有主机。因此,我将ipadress libraryhosts()函数一起使用:

import subprocess
import ipaddress

if __name__ == "__main__":
    #host='8.8.8.8'
    #subprocess.run(["host", host])
    f=open('ip.txt', 'r')
    for line in f:
        #subprocess.run(["host", line])
        newLine=line+''
        newLine=newLine[:-1]#remove EOL
        #print(newLine)
        myList=ipaddress.ip_network(u''+newLine, False)#create the object
        list(myList.hosts())
        print(list)
        for i in list:
            subprocess.run(["host", i])

当前我的列表为空

adriano@K62606:~/findRoute$ python3 workingWithMask.py <class 'list'> <class 'list'>

因此,我得到了错误:

<class 'list'>
Traceback (most recent call last):
  File "workingWithMask.py", line 16, in <module>
    for i in list:
TypeError: 'type' object is not iterable

精确地说,文件已正确读取

python-3.x ip-address
2个回答
0
投票
myList = ipaddress.ip_network(u''+newLine, False)
list(myList.hosts())
print(list)
for i in list:

您将myList.hosts()转换为列表但将其丢弃,然后打印内置类型list,然后尝试对其进行遍历,这根本没有任何意义。

您必须将myList.hosts()的结果保留在某个地方,然后对其进行迭代。

考虑:

myList = list(ipaddress.ip_network(u''+newLine, False).hosts())
print(myList)
for i in myList:
    subprocess.run(["host", i])

-1
投票

您正在使用作为类的列表关键字。尝试下面的代码:

        list(myList.hosts())
        print(list(myList.hosts()))
        for i in list(myList.hosts()):
            subprocess.run(["host", i])
© www.soinside.com 2019 - 2024. All rights reserved.