我有一个包含不同IP地址范围和不同子网的文件。我现在想获取所有范围的所有主机。因此,我将ipadress library与hosts()
函数一起使用:
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
精确地说,文件已正确读取
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])
您正在使用作为类的列表关键字。尝试下面的代码:
list(myList.hosts())
print(list(myList.hosts()))
for i in list(myList.hosts()):
subprocess.run(["host", i])