python中的快速ping扫描
因此,我尝试使用python获得与bash脚本类似的结果 bash脚本的代码:python中的快速ping扫描,python,bash,python-2.7,ping,Python,Bash,Python 2.7,Ping,因此,我尝试使用python获得与bash脚本类似的结果 bash脚本的代码: #!/bin/bash for ip in $(seq 1 254); do ping -c 1 10.10.10.$ip | grep "bytes from" | cut -d " " -f 4 | cut -d ":" -f 1 & done 我想做的事情是以相似的速度得到相同的结果。我对python脚本的每一个版本都有一个问题,即与批处理脚本所需的几秒钟相比
#!/bin/bash
for ip in $(seq 1 254); do
ping -c 1 10.10.10.$ip | grep "bytes from" | cut -d " " -f 4 | cut -d ":" -f 1 &
done
我想做的事情是以相似的速度得到相同的结果。我对python脚本的每一个版本都有一个问题,即与批处理脚本所需的几秒钟相比,它需要很长时间才能完成
批处理文件扫描a/24网络大约需要2秒,而使用python脚本所能获得的最佳时间大约是5-8分钟 python脚本的最新版本:
import subprocess
cmdping = "ping -c1 10.10.10."
for x in range (2,255):
p = subprocess.Popen(cmdping+str(x), shell=True, stderr=subprocess.PIPE)
while True:
out = p.stderr.read(1)
if out == '' and p.poll() != None:
break
if out != '':
sys.stdout.write(out)
sys.stdout.flush()
我在python中尝试了几种不同的方法,但都没有达到bash脚本的速度
有什么建议吗
你能说得更具体一点吗?与“几秒钟”相比,“非常长的时间”有多长?bash脚本末尾的符号导致进程在后台运行。你的Python脚本一个接一个地运行它们。批处理文件扫描a/24网络大约需要2秒,而我用Python脚本所能得到的最好时间大约是5-8分钟。@Blender:哈!我错过了
&
。是的,这显然是一个关键点。这里是(不需要多处理)。下面是一个关于作业的用途。放置(无)
@mojo@Isaias每一个“无”都是没有更多工作的信号。如果修改工作进程代码,您可能会结束()队列并获得类似的结果。
#!/usr/bin/python2
import multiprocessing
import subprocess
import os
def pinger( job_q, results_q ):
DEVNULL = open(os.devnull,'w')
while True:
ip = job_q.get()
if ip is None: break
try:
subprocess.check_call(['ping','-c1',ip],
stdout=DEVNULL)
results_q.put(ip)
except:
pass
if __name__ == '__main__':
pool_size = 255
jobs = multiprocessing.Queue()
results = multiprocessing.Queue()
pool = [ multiprocessing.Process(target=pinger, args=(jobs,results))
for i in range(pool_size) ]
for p in pool:
p.start()
for i in range(1,255):
jobs.put('192.168.1.{0}'.format(i))
for p in pool:
jobs.put(None)
for p in pool:
p.join()
while not results.empty():
ip = results.get()
print(ip)