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)
  • 相关阅读:
    java基础
    mysql入门
    基础整理
    遍历列表的两种方式
    oracle常用操作
    DIV+CSS网页布局技巧实例1:设置网页整体居中的代码
    html+css 淘宝首页静态页面案例
    WEB前端开发规范文档+CSS命名规范
    day05-苏宁易购导航html
    day04-html
  • 原文地址:https://www.cnblogs.com/kevincaptain/p/11698830.html
Copyright © 2011-2022 走看看