Skip to content

Instantly share code, notes, and snippets.

@rpromyshlennikov
Last active July 11, 2017 13:14
Show Gist options
  • Save rpromyshlennikov/fb38e648b82f524fe2a1d5368e3f2a6b to your computer and use it in GitHub Desktop.
Save rpromyshlennikov/fb38e648b82f524fe2a1d5368e3f2a6b to your computer and use it in GitHub Desktop.
Network interruption reporter (based on simple ping cmd output analyzis)
import datetime as dt
import re
import subprocess
import sys
HOST = "ya.ru"
FILE_NAME_TEMPLATE = "ping_report_{}.txt"
def get_dt_from_line(line):
return dt.datetime.fromtimestamp(int(line[1:11]))
def parse_icmp_seq(line):
return int(re.search("icmp_seq=(\d+)", line).group(1))
def report_fail(filename, prev_line, curr_line):
with open("{}".format(filename), "a") as report_file:
prev_dt = get_dt_from_line(prev_line)
curr_dt = get_dt_from_line(curr_line)
delta_time = (curr_dt - prev_dt).total_seconds()
report_file.write(
"Network was unavailable from {} to {} for {} seconds\n".format(
prev_dt.isoformat(), curr_dt.isoformat(), delta_time))
def main_loop(host=HOST):
report_file_name = FILE_NAME_TEMPLATE.format(host)
ping_proc = subprocess.Popen(("ping", "-D", "{}".format(host)),
stdout=subprocess.PIPE)
curr_seq = prev_seq = 1
prev_line = ""
for line in iter(ping_proc.stdout.readline, ''):
if not line:
break
if "icmp_seq" in line:
curr_seq = parse_icmp_seq(line)
if curr_seq > prev_seq + 1:
report_fail(report_file_name, prev_line, line)
prev_seq = curr_seq
prev_line = line
if __name__ == '__main__':
host = sys.argv[1] if len(sys.argv) == 2 else HOST
main_loop(host)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment