Skip to content

Instantly share code, notes, and snippets.

@tyler-8
Last active January 17, 2017 18:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tyler-8/c94bdbab4f4d181eb3f3bbc39817e639 to your computer and use it in GitHub Desktop.
Save tyler-8/c94bdbab4f4d181eb3f3bbc39817e639 to your computer and use it in GitHub Desktop.
Simple function for pinging an IP/hostname (Linux/Mac Only)
import re
import subprocess
def ping(host):
""" Ping the address/hostname and return True if packet loss is less than
60%. All other results return False or print and error."""
exp = re.compile(r"\s(\d{1,3})\%\s")
try:
test = subprocess.Popen(["ping", "-c 5", "-W 2", host],
stdout=subprocess.PIPE, stderr=subprocess.PIPE)
out, error = test.communicate()
if out:
stats = re.search(exp, out)
loss = int(stats.group(1))
return loss <= 60
else:
return False
except subprocess.CalledProcessError:
return False
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment