The examples in this article describe how Python implements a fast multithreaded ping. Share to everyone for your reference. Specific as follows:
#!/usr/bin/python#_*_coding:utf-8_*_# "Name: Fast multithreaded Ping program development: Gyhong gyh9711 Date: 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,mi nute,0) #print ("[%s] host [%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] timeout%s"% (curtime,self. IP) elif Check = = 1:print ("[%s]%s up to"% (CURTIME,SELF.IP)) Else:print ("[%s] host%s unreachable"% (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========= problem host Case ==========\n") #output (Report_ Error) #print ("\n========= normal host condition as follows ==========\n") #output (REPORT_OK)
Execution Result:
administrator@nagios:/win/pexpect$./ping.py
[2011-04-25 21:30:22.126981] 192.168.1.1 to reach
[2011-04-25 21:30:22.148376] 192.168.1.1 to reach
[2011-04-25 21:30:22.179846] 192.168.1.1 to reach
[2011-04-25 21:30:22.203691] 192.168.1.1 to reach
[2011-04-25 21:30:22.227696] 192.168.2.1 to reach
[2011-04-25 21:30:22.134049] Timeout 192.168.1.123
[2011-04-25 21:30:22.145610] timeout 192.168.2.1
[2011-04-25 21:30:22.157558] Timeout 192.168.1.123
[2011-04-25 21:30:22.167898] timeout 192.168.2.1
[2011-04-25 21:30:22.197572] Timeout 192.168.1.123
[2011-04-25 21:30:22.202430] timeout 192.168.2.1
[2011-04-25 21:30:22.215561] Timeout 192.168.1.123
[2011-04-25 21:30:22.229952] Timeout 192.168.1.1
Hopefully this article will help you with Python programming.