在Python快速ping扫描 [英] Fast ping sweep in python
问题描述
所以,我试图让使用python类似的结果,因为我有一个bash脚本做的。
code的bash脚本:
#!/斌/庆典 知识产权在$(SEQ 1 254);做
平安-c 1 10.10.10 $ IP | grep的字节由|切-d-f 4 |切-d:-f 1安培;
DONE
这是我想要做的事情是让具有相似的速度相同的结果。我已经与Python脚本的每一个版本的问题是,它需要很长的时间相比,几秒钟批处理脚本需要完成。
该批处理文件大约需要2秒钟扫/ 24网络,而我可以用python脚本获得最佳约5-8分钟。
python脚本的最新版本:
导入子cmdping =平-C1 10.10.10。在范围(2255)X:
P = subprocess.Popen(cmdping + STR(X),壳= TRUE,标准错误= subprocess.PIPE) 而真正的:
出= p.stderr.read(1)
如果出==''和p.poll()=无!
打破
如果超出=''!
sys.stdout.write函数(出)
sys.stdout.flush()
我试过在Python几种不同的方式,但不能得到批处理脚本的速度附近的任何地方。
有什么建议?
多重
#!的/ usr / bin中/ python2进口多
进口子
进口OS高清平儿(job_q,results_q):
DEVNULL =开(os.devnull,'W')
而真正的:
IP = job_q.get()
如果IP是无:突破 尝试:
subprocess.check_call(['平',' - C1',IP]
标准输出= DEVNULL)
results_q.put(IP)
除:
通过如果__name__ =='__main__':
pool_size = 255 工作= multiprocessing.Queue()
结果= multiprocessing.Queue() 池= [multiprocessing.Process(目标=瓶儿,ARGS =(工作,结果))
因为我在范围内(pool_size) 在池号码:
p.start() 在范围(1,255)I:
jobs.put('192.168.1。{0}。格式(I)) 在池号码:
jobs.put(无) 在池号码:
p.join() 同时不results.empty():
IP = results.get()
打印(IP)
So, I'm trying to get similar results using python as I do with a bash script.
Code for the bash script:
#!/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
The thing that I would like to do is get the same results with similar speed. The issue that I've had with every version of the python script is that it takes a very long time to complete compared to the few seconds the batch script takes.
The batch file takes about 2 seconds to sweep a /24 network while the the best I can get with the python script is about 5-8 minutes.
Latest version of python script:
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()
I've tried several different ways in python but can't get anywhere near the speed of the batch script.
Any suggestions?
Multiprocessing
#!/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)
这篇关于在Python快速ping扫描的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!