Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Local network pinging in python

Does anyone know how to use python to ping a local host to see if it is active or not? We (my team and I) have already tried using

os.system("ping 192.168.1.*") 

But the response for destination unreachable is the same as the response for the host is up.

Thanks for your help.

like image 437
Justin Gardner Avatar asked Oct 06 '11 17:10

Justin Gardner


People also ask

How do I ping a network in Python?

If you don't need to support Windows, here's a really concise way to do it: import os hostname = "google.com" #example response = os. system("ping -c 1 " + hostname) #and then check the response... if response == 0: print hostname, 'is up! ' else: print hostname, 'is down!


2 Answers

The best way I could find to do this on Windows, if you don't want to be parsing the output is to use Popen like this:

num = 1
host = "192.168.0.2"
wait = 1000

ping = Popen("ping -n {} -w {} {}".format(num, wait, host),
             stdout=PIPE, stderr=PIPE)  ## if you don't want it to print it out
exit_code = ping.wait()

if exit_code != 0:
    print("Host offline.")
else:
    print("Host online.")  

This works as expected. The exit code gives no false positives. I've tested it in Python 2.7 and 3.4 on Windows 7 and Windows 10.

like image 174
Daniel F. Avatar answered Sep 23 '22 21:09

Daniel F.


I've found that using os.system(...) leads to false positives (as the OP said, 'destination host unreachable' == 0).

As stated before, using subprocess.Popen works. For simplicity I recommend doing that followed by parsing the results. You can easily do this like:

if ('unreachable' in output):
        print("Offline")

Just check the various outputs you want to check from ping results. Make a 'this' in 'that' check for it.

Example:

import subprocess

hostname = "10.20.16.30"
output = subprocess.Popen(["ping.exe",hostname],stdout = subprocess.PIPE).communicate()[0]

print(output)

if ('unreachable' in output):
    print("Offline")
like image 25
Michael Flyger Avatar answered Sep 22 '22 21:09

Michael Flyger