Multiple ping script in Python

kuiper picture kuiper · Aug 24, 2012 · Viewed 121.6k times · Source

I'm unable to find any good easy to learn documentation on python and networking. In this instance, I'm just trying to make a easy script which I can ping a number of remote machines.

for ping in range(1,10):
   ip="127.0.0."+str(ping)
   os.system("ping -c 3 %s" % ip)

A simple script like that will ping the machines fine, but I'd like to get the script to returns 'active' 'no response' Which makes me think I'll have to look up the time module as well, I think time.sleep(5) and after that, there would be a break statement. Which makes me think there should be a while loop inside for. I'm not 100% sure, I could be going in the wrong direction completely :/ if anyone could help or point me in the direction of some documentation that'd be great.

Answer

Roland Smith picture Roland Smith · Aug 24, 2012

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!"