加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

python多线程实现ping多个ip

发布时间:2020-12-20 10:16:31 所属栏目:Python 来源:网络整理
导读:# !/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_forma
#!/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)

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读