由於定位網絡問題時,經常要ping,並且有時候要長時間同時ping多地址,系統自帶的ping不夠用 ,所以自己用python實現一個,用py2exe編譯為exe程序後可以方便發布。
- import time
- import string
- import thread
- import os
-
- ping_ip = []
- times = -1
- delay = 0
- ping_cmd = 'ping [ip]'
- result_file = 'result.txt'
- thread_count = 0
-
-
- def log(f, s):
- fp = open(f, 'a')
- fp.write(s)
- fp.close()
- return
-
- def doping(ip):
- ping = ping_cmd
- ping = ping.replace('[ip]', ip)
- ping = ping.replace('[result_file]', result_file)
- log_str = '\n' + ping + '\n' + time.asctime() + '\n'
- line = os.popen(ping).read()
- log_str = log_str + line + '\n'
- print log_str
- log(result_file, log_str)
-
- time.sleep(delay)
- return
-
- def ping_thread(ip, times):
- global thread_count
- if times == -1:
- while True:
- doping(ip)
- return
- for t in range(0, times):
- doping(ip)
- thread_count = thread_count - 1
- return
-
- fp = open('exping.cfg')
- for line in fp:
- line = line.strip()
- if line[0:1] == '#':
- continue
- t = line.split('=')
- if len(t) <= 1:
- continue
- if 'ip' == t[0]:
- ping_ip.append(t[1])
- elif 'times' == t[0]:
- times = string.atoi(t[1])
- elif 'delay' == t[0]:
- delay = string.atoi(t[1])
- elif 'cmd' == t[0]:
- ping_cmd = t[1]
- elif 'result_file' == t[0]:
- result_file = t[1]
- fp.close()
-
- for ip in ping_ip:
- thread_count = thread_count + 1
- thread.start_new_thread(ping_thread, (ip, times))
-
- while True:
- if thread_count == 0:
- break
- time.sleep(5)
配置文件:
- #執行次數
- times=2
-
- #每次執行後的時間延遲
- delay=5
-
- #結果輸出文件
- result_file=result.txt
-
- #ping命令
- cmd=ping -c 1 [ip]
-
- #要ping的ip地址,可以任意多個,每個會啟用一個線程
- ip=192.168.1.1
- ip=www.linuxidc.com
- ip=218.18.168.160