Last active
January 17, 2017 18:57
-
-
Save tyler-8/c94bdbab4f4d181eb3f3bbc39817e639 to your computer and use it in GitHub Desktop.
Simple function for pinging an IP/hostname (Linux/Mac Only)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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