Home > Net >  Python, efficent way to ping multiple host
Python, efficent way to ping multiple host

Time:05-05

I wrote a simple python script ( on Windows machine) which ping every host on a list. The scripts works quite good but when the number of host increases the scripts is very slow.

How can I improve my script to test a large number of host in efficent way?

Below a snippet of my script:

ip = ["192.168.1.61","192.168.1.65","192.168.1.66","192.168.1.33","192.168.1.4","192.168.1.5","192.168.1.213","192.168.1.215","192.168.1.217","192.168.1.226","192.168.1.227"]
# lista dei risultati
results = [False] * len(ip)


#TEST
def testPing():
        devnull = open(os.path.devnull, 'wb')
        n = 0
        while n < len(ip):
                result=subprocess.Popen(["ping", "-n", "1", "-w", "200", ip[n]],
                        stdout=devnull, stderr=devnull).wait()
                if result:
                        #print ( ip[n], "inactive")
                        results[n]=False
                else:
                        #print ( ip[n], "active")
                        results[n]=True
                n  = 1

CodePudding user response:

You can ping the targets with this https://stackoverflow.com/a/33018614/16090441

And for the speed of it, i would recommend using multiprocessing

You could split the list into say 3 parts and then run 3 threads to ping all the targets at once.

CodePudding user response:

This thread solution by Robert N seems to work well and is quite fast. The workaround is decreasing the timeout value so your script does not hang too long on offline hosts. If the speed is still not as expected you can look into threading. Then with threading or in general I would recommend appending each offline/online host ip to an array and displaying it in the end of the loop or echoing to a text document for better readability. Hope this helps!

Best regards, Koenry

  • Related