Skip to content

Instantly share code, notes, and snippets.

@tekton
Created December 21, 2016 14:28
Show Gist options
  • Save tekton/b4e3fcb4dc853c35c07786eb2a937786 to your computer and use it in GitHub Desktop.
Save tekton/b4e3fcb4dc853c35c07786eb2a937786 to your computer and use it in GitHub Desktop.
process ping output in python
import subprocess
import re
regex = "(?P<bytes>\d+) bytes from (?P<ip>\d{1,3}.\d{1,3}.\d{1,3}.\d{1,3}): icmp_seq=(?P<icmp>\d+) ttl=(?P<ttl>\d+) time=(?P<ms>\d+.\d+) ms"
r = re.compile(regex)
# compiling ahead of time speeds up other runs when more than one server is needed to be reached
def ping_server(ip="localhost", count=10, *args, **kwargs):
rtn_list = []
ping_response = subprocess.Popen(["ping", "-c{}".format(int(count)), ip], stdout=subprocess.PIPE).stdout.read()
# technically we could find the location of ping, but that gets weird across all platforms (ie windows)
lines = ping_response.splitlines()
for line in lines:
d = r.match(line)
if d is not None:
"""
Checking for none here greatly reduces our error handling
"""
rtn_list.append({
"bytes": d.group("bytes"),
"ip": d.group("ip"),
"icmp": d.group("icmp"),
"ttl": d.group("ttl"),
"ms": d.group("ms")
})
return rtn_list
if __name__ == "__main__":
print(ping_server())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment