python多线程实现ping多个ip

#!/usr/bin/env python
# -*- coding:utf-8 -*-

import  subprocess
import logging
import datetime
import time
import threading
try:
    # Python3
    from queue import Queue
except ImportError:
    # Python2
    from Queue import Queue


def set_logging_format():
    logging.basicConfig(level=logging.INFO,
        format='%(message)s',
        filename="ping_host.log",
        filemode='w'
    )
    console = logging.StreamHandler()
    console.setLevel(logging.INFO)
    formatter = logging.Formatter('%(message)s')
    console.setFormatter(formatter)
    logging.getLogger('').addHandler(console)


# 将需要 ping 的 ip 加入队列
def insert_ip_queue(hosts_list_path):
    IP_QUEUE = Queue()
    with open(hosts_list_path, "r") as f:
        for host in f.readlines():
            IP_QUEUE.put(host)
    return IP_QUEUE


# 定义一个执行 ping 的函数
def ping_host(IP_QUEUE):
    while not IP_QUEUE.empty():
        ip = IP_QUEUE.get().strip("\n")
        popen = subprocess.Popen('ping -c 1 -w 1 %s' %ip, stdout=subprocess.PIPE,shell=True)
        popen.wait()
        res = popen.stdout.read()
        if "1 received" in res:
            res = "success"
        else:
            res = "fail"
        today = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        logging.info("%s  %s %s" % (today,ip,res ))


if __name__ == '__main__':
    set_logging_format()
    hosts_list_path  = "./sgdev-hostip.txt"

    # 定义工作线程
    WORD_THREAD_NUM = 30

    while True:
        IP_QUEUE = insert_ip_queue(hosts_list_path)
        threads = []
        for i in range(WORD_THREAD_NUM):
            thread = threading.Thread(target=ping_host,args=(IP_QUEUE,))
            thread.start()
            threads.append(thread)

        for thread in threads:
            thread.join()
        #print("******next run************************************")
        time.sleep(30)

 

你可能感兴趣的:(python多线程实现ping多个ip)