Skip to main content
 首页 » 编程设计

python之使用 Python 发送多个 ping

2024年10月17日6JeffreyZhao

如何一次 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!' 

请您参考如下方法:

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

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)) 

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

for ip2, process in processes: 
    response = process.wait() 
    if response == 0: 
        print ip2, 'is up!' 
    else: 
        print ip2, 'is down!'