我有一个小程序通过发送 10 个 ping 同时 ping 多个 IP。这既在字典中记录结果,也将状态打印到页面。
但是,我希望允许程序不断地 ping 并让用户停止它,而不是依靠最大 ping 计数。
import os
import re
import time
import sys
import subprocess
import Queue
import threading
class pinger:
def __init__(self,hosts):
self.q = Queue.Queue()
self.all_results = []
self.hosts = hosts
def send_ping(self,q,ip):
self.q.put(self.record_results(ip))
def record_results(self,ip):
ping_count = 0
host_results = {
"host" : ip,
"device" : None,
"sent_count" : 0,
"success_count": 0,
"fail_count": 0,
"failed_perc": 0,
"curr_status": None
}
while ping_count < 10:
rc = subprocess.call(['ping', '-c', '1', '-W', '1', ip], stdout=open('/dev/null', 'w'), stderr=open('/dev/null', 'w'))
ping_count += 1
# update stats
host = host_results['host']
sent_count = host_results['sent_count']
success_count = host_results['success_count']
fail_count = host_results['fail_count']
failed_perc = host_results['failed_perc']
curr_status = host_results['curr_status']
sent_count += 1
if rc == 0:
success_count += 1
curr_status = "Successful Response"
else:
fail_count += 1
curr_status = "Request Timed Out"
failed_perc = ( fail_count / sent_count ) * 100
host_results.update({'failed_perc': failed_perc, 'fail_count': fail_count, 'success_count': success_count, 'curr_status': curr_status, 'sent_count': sent_count})
time.sleep(0.5)
print host_results
self.all_results.append(host_results)
return True
def go(self):
for i in self.hosts:
t = threading.Thread(target=self.send_ping, args = (self.q,i))
t.daemon = True
t.start()
谢谢,