打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
快速多线程ping

http://www.oschina.net/code/snippet_47318_4046

2011

python pexpect包应用一例
快速多线程ping

 

1. [代码][Python]代码      


#!/usr/bin/python
#_*_coding:utf-8_*_
#
'''
名称:快速多线程ping程序
开发:gyhong gyh9711
日期:20:51 2011-04-25
'''
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
[2011-04-25 21:30:22.126981] 192.168.1.1 可达
[2011-04-25 21:30:22.148376] 192.168.1.1 可达
[2011-04-25 21:30:22.179846] 192.168.1.1 可达
[2011-04-25 21:30:22.203691] 192.168.1.1 可达
[2011-04-25 21:30:22.227696] 192.168.2.1 可达
[2011-04-25 21:30:22.134049] 超时 192.168.1.123
[2011-04-25 21:30:22.145610] 超时 192.168.2.1
[2011-04-25 21:30:22.157558] 超时 192.168.1.123
[2011-04-25 21:30:22.167898] 超时 192.168.2.1
[2011-04-25 21:30:22.197572] 超时 192.168.1.123
[2011-04-25 21:30:22.202430] 超时 192.168.2.1
[2011-04-25 21:30:22.215561] 超时 192.168.1.123
[2011-04-25 21:30:22.229952] 超时 192.168.1.1
本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
ssh批量登录并执行命令(python实现)
Python多线程批量Ping主机IP的脚本
从volatile说到i++的线程安全问题
python多线程编程(1): python对多线程的支持
c#实现每隔一段时间执行代码(多线程)-程序开发-红黑联盟
c#中使用多线程访问winform中控件
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服