networking – Multiple ping script in Python

networking – Multiple ping script in Python

Try subprocess.call. It saves the return value of the program that was used.

According to my ping manual, it returns 0 on success, 2 when pings were sent but no reply was received and any other value indicates an error.

# typo error in import
import subprocess

for ping in range(1,10):
    address = 127.0.0. + str(ping)
    res = subprocess.call([ping, -c, 3, address])
    if res == 0:
        print ping to, address, OK
    elif res == 2:
        print no response from, address
    else:
        print ping to, address, failed!

This script:

import subprocess
import os
with open(os.devnull, wb) as limbo:
        for n in xrange(1, 10):
                ip=192.168.0.{0}.format(n)
                result=subprocess.Popen([ping, -c, 1, -n, -W, 2, ip],
                        stdout=limbo, stderr=limbo).wait()
                if result:
                        print ip, inactive
                else:
                        print ip, active

will produce something like this output:

192.168.0.1 active
192.168.0.2 active
192.168.0.3 inactive
192.168.0.4 inactive
192.168.0.5 inactive
192.168.0.6 inactive
192.168.0.7 active
192.168.0.8 inactive
192.168.0.9 inactive

You can capture the output if you replace limbo with subprocess.PIPE and use communicate() on the Popen object:

p=Popen( ... )
output=p.communicate()
result=p.wait()

This way you get the return value of the command and can capture the text. Following the manual this is the preferred way to operate a subprocess if you need flexibility:

The underlying process creation and management in this module is
handled by the Popen class. It offers a lot of flexibility so that
developers are able to handle the less common cases not covered by the
convenience functions.

networking – Multiple ping script in Python

Thank you so much for this. I have modified it to work with Windows. I have also put a low timeout so, the IPs that have no return will not sit and wait for 5 seconds each. This is from hochl source code.

import subprocess
import os
with open(os.devnull, wb) as limbo:
        for n in xrange(200, 240):
                ip=10.2.7.{0}.format(n)
                result=subprocess.Popen([ping, -n, 1, -w, 200, ip],
                        stdout=limbo, stderr=limbo).wait()
                if result:
                        print ip, inactive
                else:
                        print ip, active

Just change the ip= for your scheme and the xrange for the hosts.

Leave a Reply

Your email address will not be published. Required fields are marked *