所以,我正在尝试使用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脚本都遇到了问题,与批处理脚本仅需几秒钟完成相比,Python脚本需要很长时间才能完成。
批处理文件大约需要2秒钟扫描/24网络,而我最好的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脚本。
有什么建议吗?
&
。是的,那显然是一个关键点。 - Greg Hewgillmultiprocessing
)。这是一个代码示例,限制并发ping数量。 - jfs