Python實現快速多線程ping的方法

來源:互聯網
上載者:User
本文執行個體講述了Python實現快速多線程ping的方法。分享給大家供大家參考。具體如下:

#!/usr/bin/python#_*_coding:utf-8_*_#'''名稱:快速多線程ping程式開發:gyhong gyh9711日期:20:51 2011-04-25'''import pexpectimport datetimefrom threading import Threadhost=["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

希望本文所述對大家的Python程式設計有所協助。

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.