当前位置:Gxlcms > Python > Python实现快速多线程ping的方法

Python实现快速多线程ping的方法

时间:2021-07-01 10:21:17 帮助过:13人阅读

本文实例讲述了Python实现快速多线程ping的方法。分享给大家供大家参考。具体如下:

  1. #!/usr/bin/python
  2. #_*_coding:utf-8_*_
  3. #
  4. '''
  5. 名称:快速多线程ping程序
  6. 开发:gyhong gyh9711
  7. 日期:20:51 2011-04-25
  8. '''
  9. import pexpect
  10. import datetime
  11. from threading import Thread
  12. host=["192.168.1.1","192.168.1.123","192.168.2.1",
  13. "192.168.1.1","192.168.1.123","192.168.2.1",
  14. "192.168.1.1","192.168.1.123","192.168.2.1",
  15. "192.168.1.1","192.168.1.123","192.168.2.1",
  16. "192.168.1.1"]
  17. report_ok=[]
  18. report_error=[]
  19. class PING(Thread):
  20. def __init__(self,ip):
  21. Thread.__init__(self)
  22. self.ip=ip
  23. def run(self):
  24. Curtime = datetime.datetime.now()
  25. #Scrtime = Curtime + datetime.timedelta(0,minute,0)
  26. #print("[%s]主机[%s]" % (Curtime,self.ip))
  27. ping=pexpect.spawn("ping -c1 %s" % (self.ip))
  28. check=ping.expect([pexpect.TIMEOUT,"1 packets transmitted, 1 received, 0% packet loss"],2)
  29. if check == 0:
  30. print("[%s] 超时 %s" % (Curtime,self.ip))
  31. elif check == 1:
  32. print ("[%s] %s 可达" % (Curtime,self.ip))
  33. else:
  34. print("[%s] 主机%s 不可达" % (Curtime,self.ip))
  35. #多线程同时执行
  36. T_thread=[]
  37. for i in host:
  38. t=PING(i)
  39. T_thread.append(t)
  40. for i in range(len(T_thread)):
  41. T_thread[i].start()
  42. #
  43. #print ("\n=========问题主机情况如下==========\n")
  44. #output(report_error)
  45. #print ("\n=========正常主机情况如下==========\n")
  46. #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程序设计有所帮助。

人气教程排行