Welcome 微信登录
编程资源 图片资源库 蚂蚁家优选 PDF转换器

首页 / 操作系统 / Linux / Python实现增强版Ping

由于定位网络问题时,经常要ping,并且有时候要长时间同时ping多地址,系统自带的ping不够用 ,所以自己用python实现一个,用py2exe编译为exe程序后可以方便发布。
  1. import time  
  2. import string  
  3. import thread  
  4. import os  
  5.   
  6. ping_ip = []  
  7. times = -1  
  8. delay = 0  
  9. ping_cmd = "ping [ip]"  
  10. result_file = "result.txt"  
  11. thread_count = 0  
  12.   
  13.   
  14. def log(f, s):  
  15.     fp = open(f, "a")  
  16.     fp.write(s)  
  17.     fp.close()  
  18.     return  
  19.   
  20. def  doping(ip):  
  21.     ping = ping_cmd  
  22.     ping = ping.replace("[ip]", ip)  
  23.     ping = ping.replace("[result_file]", result_file)  
  24.     log_str = " " + ping + " " + time.asctime() + " "  
  25.     line = os.popen(ping).read()  
  26.     log_str = log_str + line + " "  
  27.     print log_str  
  28.     log(result_file, log_str)  
  29.           
  30.     time.sleep(delay)  
  31.     return  
  32.   
  33. def ping_thread(ip, times):  
  34.     global thread_count  
  35.     if times == -1:  
  36.         while True:  
  37.             doping(ip)  
  38.         return  
  39.     for t in range(0, times):  
  40.         doping(ip)  
  41.     thread_count = thread_count - 1  
  42.     return  
  43.   
  44. fp = open("exping.cfg")  
  45. for line in fp:  
  46.     line = line.strip()  
  47.     if line[0:1] == "#":  
  48.         continue  
  49.     t = line.split("=")  
  50.     if len(t) <= 1:  
  51.         continue  
  52.     if "ip" == t[0]:  
  53.         ping_ip.append(t[1])  
  54.     elif "times" == t[0]:  
  55.         times = string.atoi(t[1])  
  56.     elif "delay" == t[0]:  
  57.         delay = string.atoi(t[1])  
  58.     elif "cmd" == t[0]:  
  59.         ping_cmd = t[1]     
  60.     elif "result_file" == t[0]:  
  61.         result_file = t[1]  
  62. fp.close()  
  63.   
  64. for ip in ping_ip:  
  65.     thread_count = thread_count + 1  
  66.     thread.start_new_thread(ping_thread, (ip, times))  
  67.   
  68. while True:  
  69.     if thread_count == 0:  
  70.         break  
  71.     time.sleep(5)  
配置文件:
  1. #执行次数   
  2. times=2  
  3.   
  4. #每次执行后的时间延迟   
  5. delay=5  
  6.   
  7. #结果输出文件   
  8. result_file=result.txt  
  9.   
  10. #ping命令   
  11. cmd=ping -c 1 [ip]  
  12.   
  13. #要ping的ip地址,可以任意多个,每个会启用一个线程   
  14. ip=192.168.1.1  
  15. ip=www.linuxidc.com  
  16. ip=218.18.168.160