前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Python: ping网段内所有ip并

Python: ping网段内所有ip并

作者头像
py3study
发布2020-01-08 10:57:04
2.1K0
发布2020-01-08 10:57:04
举报
文章被收录于专栏:python3python3

    今天用Python写了一段小代码,实现的功能是ping某一个网段的所有ip,然后将ping的结果提取出来,输出可以ping通的ip以及往返时间。

    初学Python,写得简陋,各位大侠多多指教。

  1. 正则表达式请根据自己的系统进行调整,我这个是中文win7下的结果
  2. Python3.3下测试没问题
  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.')
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2019-09-07 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档