前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Python快速多线程ping实现

Python快速多线程ping实现

原创
作者头像
大师级码师
修改2021-09-22 10:52:22
5650
修改2021-09-22 10:52:22
举报
文章被收录于专栏:大师级码师大师级码师
代码语言:javascript
复制
#!/usr/bin/python
_coding:utf-8_
#
'''
名称:快速多线程ping程序
'''
import pexpect
import datetime
from threading import Thread
host=["192.168.1.1","192.168.1.123","192.168.2.1",
"192.168.1.1","192.168.1.123","192.168.2.1",
"192.168.1.1","192.168.1.123","192.168.2.1",
"192.168.1.1","192.168.1.123","192.168.2.1",
"192.168.1.1"]
report_ok=[]
report_error=[]
class PING(Thread):
    def init(self,ip):
        Thread.init(self)
        self.ip=ip
    def run(self):
        Curtime = datetime.datetime.now()

    #Scrtime = Curtime + datetime.timedelta(0,minute,0)
    #print("[%s]主机[%s]" % (Curtime,self.ip))
    ping=pexpect.spawn("ping -c1 %s" % (self.ip))
    check=ping.expect([pexpect.TIMEOUT,"1 packets transmitted, 1 received, 0% packet loss"],2)
    if check == 0:
        print("[%s] 超时 %s" % (Curtime,self.ip))

    elif check == 1:
        print ("[%s] %s 可达" % (Curtime,self.ip))

    else:
        print("[%s] 主机%s 不可达" % (Curtime,self.ip))


 
多线程同时执行
T_thread=[]
for i in host:
    t=PING(i)
    T_thread.append(t)
for i in range(len(T_thread)):
    T_thread[i].start()
#
print ("\n=========问题主机情况如下==========\n")
output(report_error)
print ("\n=========正常主机情况如下==========\n")
output(report_ok)
执行结果:
administrator@nagios:/win/pexpect$ ./ping.py
[2014-04-25 21:30:22.126981] 192.168.1.1 可达
[2014-04-25 21:30:22.148376] 192.168.1.1 可达
[2014-04-25 21:30:22.179846] 192.168.1.1 可达
[2014-04-25 21:30:22.203691] 192.168.1.1 可达
[2014-04-25 21:30:22.227696] 192.168.2.1 可达
[2014-04-25 21:30:22.134049] 超时 192.168.1.123
[2014-04-25 21:30:22.145610] 超时 192.168.2.1
[2014-04-25 21:30:22.157558] 超时 192.168.1.123
[2014-04-25 21:30:22.167898] 超时 192.168.2.1
[2014-04-25 21:30:22.197572] 超时 192.168.1.123
[2014-04-25 21:30:22.202430] 超时 192.168.2.1
[2014-04-25 21:30:22.215561] 超时 192.168.1.123
[2014-04-25 21:30:22.229952] 超时 192.168.1.1</pre> 

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

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

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

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

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