zoukankan      html  css  js  c++  java
  • 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("
    ")
            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)
  • 相关阅读:
    常用JSR-303数据校验
    SpringBoot配置文件及自动配置原理
    SpringBoot自动装配原理
    Centos安装TensorFlow和Keras
    Batch梯度下降
    梯度下降法的注意点
    读取流量
    Linux开机启动服务
    Shell分割字符得到数组
    Linux下无图形界面安装Matlab
  • 原文地址:https://www.cnblogs.com/kevincaptain/p/11698830.html
Copyright © 2011-2022 走看看