Python实现增强版Ping
Python实现增强版Ping
由于定位网络问题时,经常要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.bkjia.com
- ip=218.18.168.160
评论暂时关闭