Pinging servers in Python

Kudu picture Kudu · Jun 1, 2010 · Viewed 522.1k times · Source

In Python, is there a way to ping a server through ICMP and return TRUE if the server responds, or FALSE if there is no response?

Answer

Scott picture Scott · May 1, 2012

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

This works because ping returns a non-zero value if the connection fails. (The return value actually differs depending on the network error.) You could also change the ping timeout (in seconds) using the '-t' option. Note, this will output text to the console.