繁体   English   中英

Python中IP地址的多线程ping

[英]multithread pinging of IP address in Python

我有一个 IP 地址列表,比如 1000 个没有。 我正在读取 ip_file.txt 并将结果文件存储为 result_date.txt。 下面是我实现结果的代码。 但我的问题是执行整个文件需要很长时间。 任何人都可以建议多线程,以便可以快速达到预期的结果? 提前致谢。

#!/usr/bin/env python
import os
import csv
import paramiko
from datetime import datetime
import time
import sys
import re
from collections import defaultdict

# Verifies your os type
from paramiko import file

OS_TYPE = os.name
# Sets the count modifier to the os type
count = '-n' if OS_TYPE == 'nt' else '-c'


def create_ip_list():
    ip_list = []
    with open("ip_file.txt", "r") as file:
        for line in file:
            ip_list.append(line.strip())
    return ip_list

# fetching data
now = datetime.now()
dat = now.strftime("%d/%m/%Y")
# time = now.strftime("%H:%M:%S")
date_string = dat.replace('/', '-')

timestr = time.strftime("%d%m%Y-%H%M%S")


def ping_device(ip_list):
    """Ping ip_list and return results
        return: None
        rtype: None
    """
    results_file = open("results_" + str(timestr) + ".txt", "w")
    for ip in ip_list:
        response = os.popen(f"ping {ip} {count} 1").read()
        time.sleep(1.5)
        #fetch Average time
        print(response)
        for i in response.split("\n"):
            para = i.split("=")
            try:
                if para[0].strip() == "Minimum":
                    latency = para[3].strip()
                    print(latency)
                    # output1=latency[0:8].split(" ")
                    # test=output1[0]
                    # print(test)
            except:
                print("time run")

        if "Received = 1" and "Approximate" in response:
            #print(f"UP {ip} Ping Successful")
            results_file.write(f"{ip},UP,{latency}" + "\n")
        else:
            print(f"Down {ip} Ping Unsuccessful")
            results_file.write(f"{ip} Down" + "\n")
    results_file.close()

if __name__ == "__main__":
    ping_device(create_ip_list())

编写一个函数ping_one_device ,它接受一个ip并返回一个给出状态的字符串。 应该很容易将其从ping_device中提取出来。

然后

with open(results_file, "w") as results_file:
    with ThreadPoolExecutor() as executor:
        for result in map(ping_one_device, ip_list):
            results_file.write(result)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM