Python: ping网段内所有ip并返回结果
__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),int(result),int(result)))
return (ip,result)
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.')
页:
[1]