0

我有一个小程序通过发送 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()

谢谢,

4

1 回答 1

1

您可以将while ping_count < 10条件更改为while self.should_ping:(变量将被初始化为True)。此外,如果有一个等待收集所有结果的主循环,则可以将其包装try: except KeyboardInterrupt:并设置pinger.should_pingFalse异常处理程序。

否则,您可以注册到SIGINT信号,如@bereal 所述,并将should_ping变量设置为False那里。

于 2013-11-09T19:39:26.200 回答