遍历 IP 列表地址

Iterate over an IP list addresses

我有一个包含不同子网的不同 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

我很准确,文件读取正确

您使用的列表关键字是 class。 尝试:

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

您将 myList.hosts() 转换为列表但将其丢弃,然后打印内置 type list 然后尝试对其进行迭代,这使得完全没有意义。

您必须将 list(...) 的结果保存在某处,然后对其进行迭代。

考虑:

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