您的位置:首页 > 编程语言 > Python开发

Python: ping网段内所有ip并返回结果

2014-07-02 12:34 405 查看
       今天用Python写了一段小代码,实现的功能是ping某一个网段的所有ip,然后将ping的结果提取出来,输出可以ping通的ip以及往返时间。
      初学Python,写得简陋,各位大侠多多指教。

正则表达式请根据自己的系统进行调整,我这个是中文win7下的结果

Python3.3下测试没问题

ping测试的过程中内存占用较大,不知道可以怎么改进

__author__ = 'wucl'

import subprocess, re, _thread, queue, time, threading

print('Ping Processing, Please Wait...')

regex=re.compile('最短 = (\d+)ms,最长 = (\d+)ms,平均 = (\d+)ms')
ipPrefix='192.168.1.'
decoding='gbk'

def ping(ip):
p=subprocess.Popen(['ping.exe',ip],stdout=subprocess.PIPE)
out=p.stdout.read()
result=regex.findall(out.decode(decoding))
if result:
printQueue.put('%15s 最短=%2dms,最长=%2dms,平均=%2dms' %(ip,int(result[0][0]),int(result[0][1]),int(result[0][2])))
return (ip,result[0])

def resultPrint(printQueue):
while True:
try:
data=printQueue.get()
except queue.Empty:
pass
else:
with safeprint:
print(data)

printQueue=queue.Queue()
safeprint=_thread.allocate_lock()
thread=threading.Thread(target=resultPrint,args=(printQueue,))
thread.daemon=True
thread.start()

waitfor=[]

for i in range(1,255):
ip=ipPrefix+str(i)
thread=threading.Thread(target=ping,args=(ip,))
waitfor.append(thread)
thread.start()

for thread in waitfor:
thread.join()

print('Ping End.')
input('Press Enter to quit.')
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息