multithread pinging of IP address in Python

323 Views Asked by At

I have a list of IP addresses like 1000 no's. I am reading the ip_file.txt and storing the result file as result_date.txt. Below is the code that I achieved the result. But my issue is it's taking too long to execute the entire files. Can anyone suggest multithreading, please so that the desired result can be achieved quickly? Thanks in advance.

#!/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())
1

There are 1 best solutions below

0
Frank Yellin On

Write a function ping_one_device that takes a single ip and returns a single string giving the status. It should be easy to pull this out of ping_device.

Then

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)