排查網路故障時,ping 幾乎是無所不在的第一線工具。無奈系統內建的 ping 功能實在太過樸素:一次只能盯著一個位址,想要同時監看多台主機就得開一堆視窗,長時間掛著更是麻煩。於是我乾脆用 Python 自己寫了一個增強版,把多執行緒與批次監控一次搞定,再用 py2exe 打包成單一 exe,丟到任何一台 Windows 機器上都能直接執行,發布起來輕鬆又省事。
整個工具靠一個設定檔驅動,主程式負責讀取設定、為每個 IP 開一條執行緒,並把結果即時印在螢幕上、同步寫入指定檔案。
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
其中 times 設為 -1 代表無限循環、持續監看;delay 控制每輪之間的喘息時間;而 ip 可以列上任意多筆,每一筆都會被分配到一條獨立執行緒去跑,彼此互不干擾。對於需要長時間盯著一整批主機的維運場景來說,這個小工具比原生 ping 好用太多了。