Created
December 21, 2016 14:28
-
-
Save tekton/b4e3fcb4dc853c35c07786eb2a937786 to your computer and use it in GitHub Desktop.
process ping output in python
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 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