使用Python发送多个ping

时间:2016-08-25 22:59:33

标签: python

如何一次ping 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!' ?尝试使脚本运行得更快,因为它需要几分钟才能完成。

extends  AppCompatActivity
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbarhome);
setSupportActionBar(toolbar);

3 个答案:

答案 0 :(得分:2)

您可以立即启动所有流程并将其保存在列表中,而不是等待每个流程在循环中完成:

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!'

答案 1 :(得分:0)

查看用于获得回复的方法:

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

最重要的是,最后的.wait()表示您的程序将等到流程完成。

您可以将Popen(而不是等待)的结果放入列表中,一次启动255个进程(尽管您可能希望在完整性的情况下启动较小的块):

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

然后,您可以完成每个过程并等到完成:

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

答案 2 :(得分:0)

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