歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Python實現增強版Ping

Python實現增強版Ping

日期:2017/3/1 10:18:19   编辑:Linux編程

由於定位網絡問題時,經常要ping,並且有時候要長時間同時ping多地址,系統自帶的ping不夠用 ,所以自己用python實現一個,用py2exe編譯為exe程序後可以方便發布。

  1. import time
  2. import string
  3. import thread
  4. import os
  5. ping_ip = []
  6. times = -1
  7. delay = 0
  8. ping_cmd = 'ping [ip]'
  9. result_file = 'result.txt'
  10. thread_count = 0
  11. def log(f, s):
  12. fp = open(f, 'a')
  13. fp.write(s)
  14. fp.close()
  15. return
  16. def doping(ip):
  17. ping = ping_cmd
  18. ping = ping.replace('[ip]', ip)
  19. ping = ping.replace('[result_file]', result_file)
  20. log_str = '\n' + ping + '\n' + time.asctime() + '\n'
  21. line = os.popen(ping).read()
  22. log_str = log_str + line + '\n'
  23. print log_str
  24. log(result_file, log_str)
  25. time.sleep(delay)
  26. return
  27. def ping_thread(ip, times):
  28. global thread_count
  29. if times == -1:
  30. while True:
  31. doping(ip)
  32. return
  33. for t in range(0, times):
  34. doping(ip)
  35. thread_count = thread_count - 1
  36. return
  37. fp = open('exping.cfg')
  38. for line in fp:
  39. line = line.strip()
  40. if line[0:1] == '#':
  41. continue
  42. t = line.split('=')
  43. if len(t) <= 1:
  44. continue
  45. if 'ip' == t[0]:
  46. ping_ip.append(t[1])
  47. elif 'times' == t[0]:
  48. times = string.atoi(t[1])
  49. elif 'delay' == t[0]:
  50. delay = string.atoi(t[1])
  51. elif 'cmd' == t[0]:
  52. ping_cmd = t[1]
  53. elif 'result_file' == t[0]:
  54. result_file = t[1]
  55. fp.close()
  56. for ip in ping_ip:
  57. thread_count = thread_count + 1
  58. thread.start_new_thread(ping_thread, (ip, times))
  59. while True:
  60. if thread_count == 0:
  61. break
  62. time.sleep(5)

配置文件:

  1. #執行次數
  2. times=2
  3. #每次執行後的時間延遲
  4. delay=5
  5. #結果輸出文件
  6. result_file=result.txt
  7. #ping命令
  8. cmd=ping -c 1 [ip]
  9. #要ping的ip地址,可以任意多個,每個會啟用一個線程
  10. ip=192.168.1.1
  11. ip=www.linuxidc.com
  12. ip=218.18.168.160
Copyright © Linux教程網 All Rights Reserved