使用Python发送多个ping

2024-04-18 13:40:47 发布

您现在位置:Python中文网/ 问答频道 /正文

如何一次ping 192.168.0.1-192.168.0.254?尝试使脚本运行得更快,因为它需要几分钟才能完成。在

import os
import subprocess


ip = raw_input("IP Address? ")
print "Scanning IP Address: " + ip

subnet = ip.split(".")

FNULL = open(os.devnull, 'w')

for x in range(1, 255):
    ip2 = subnet[0]+"."+ subnet[1] +"."+ subnet[2] +"."+ str(x)
    response=subprocess.Popen(["ping", "-c", "1", "-n", "-W", "2", ip2], stdout=FNULL, stderr=subprocess.STDOUT).wait()
if response == 0:
    print ip2, 'is up!'
else:
    print ip2, 'is down!'

Tags: importip脚本rawisosaddressresponse
3条回答

无需等待循环中的每个进程完成,您可以一次启动所有进程并将其保存在列表中:

processes = []

for x in range(1, 255):
    ip2 = subnet[0]+"."+ subnet[1] +"."+ subnet[2] +"."+ str(x)
    process = subprocess.Popen(["ping", "-c", "1", "-n", "-W", "2", ip2], stdout=FNULL, stderr=subprocess.STDOUT)
    processes.append((ip2, process))

然后,您可以等待每个进程完成并打印结果:

^{pr2}$

或者你可以用一次ping到子网广播地址来ping它们。因此,如果您的子网是255.255.255.0(也称为/24),那么只需ping192.168.0.255通常每个人都会ping回来。在

看看你用来得到回应的方法:

response=subprocess.Popen(["ping", "-c", "1", "-n", "-W", "2", ip2], stdout=FNULL, stderr=subprocess.STDOUT).wait()

最重要的是,末尾的.wait()表示程序将等待进程完成。在

通过将Popen(而不是wait)的结果放入一个列表中,您可以一次启动255个进程(尽管为了正常起见,您可能需要启动较小的块):

^{pr2}$

然后,您可以完成每一个流程,直到它们完成:

for process, ip8 in zip(processes, range(1, 255)):
    ip32 = subnet[0]+"."+ subnet[1] +"."+ subnet[2] +"."+ str(ip8)
    response = process.wait()
    if response == 0:
        print("%s is up!" % (ip32))
    else:
        print("%s is down!" % (ip32))

相关问题 更多 >