Skip to content

Instantly share code, notes, and snippets.

@ara-ta3
Created February 2, 2021 16:21
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 ara-ta3/fbdde9ffe437f612eb696177ee5e5556 to your computer and use it in GitHub Desktop.
Save ara-ta3/fbdde9ffe437f612eb696177ee5e5556 to your computer and use it in GitHub Desktop.
ping.py
import argparse
from typing import NamedTuple, Dict
# 下記commandを前提にしてる
# ping -s 16 -i 1 -c 86400 google.com | LANG=C xargs -I_ gdate +'%c _' > ping.txt
def main():
parser = argparse.ArgumentParser()
parser.add_argument('infile', type=argparse.FileType('r', encoding='utf-8'))
parser.add_argument('--mode', type=str)
parser.add_argument('--csv', action='store_true')
args = parser.parse_args()
mode = args.mode
ping = Ping()
for i in args.infile:
if 'PING' in i or 'ping statistics' in i or 'packets transmitted' in i or 'round-trip' in i or 'Destination' in i or 'Vr HL TOS Len ID Flg off TTL Pro cks Src Dst' in i:
pass
elif 'Request' in i:
_, month, day, t, y, _, _, _, _, _ = i.split()
h, m, s = t.split(":")
m = None if mode is None else int(int(m) / 10) * 10
ping.plus_timeout(y, month, day, h, m)
else:
_, month, day, t, y, _, _, _, _, _, _, time_ms, _ = i.split()
h, m, s = t.split(":")
m = None if mode is None else int(int(m) / 10) * 10
_, sec = time_ms.split("=")
ping.plus_ping(y, month, day, h, m, float(sec))
if args.csv:
print("Time,N,Timeout,Ping,Avg ms")
for k, v in ping.data.items():
p = v["ping"]
t = v["timeout"]
n = p + t
avg = v["ms"] / p if p != 0 else 0
print("{},{},{},{},{}".format(k, n, t, p, avg))
else:
for k, v in ping.data.items():
p = v["ping"]
t = v["timeout"]
n = p + t
avg = v["ms"] / p if p != 0 else 0
print("{} --- N: {}, Timeout: {}, Ping: {}, Avg ms: {}".format(k, n, t, p, avg))
class Ping:
data: Dict[str, Dict[str, float]] = {}
def plus_timeout(self, year, month, day, hour, m):
key = self._to_key(year, month, day, hour, m)
self._plus(key, "timeout")
def plus_ping(self, year, month, day, hour, min, ms):
key = self._to_key(year, month, day, hour, min)
self._plus(key, "ping")
self.data[key]["ms"] += ms
def _to_key(self, year, month, day, hour, min):
return "{} {} {} {}:00".format(year, month, day, hour) if min is None else "{} {} {} {}:{}".format(year, month, day, hour, str(min).zfill(2))
def _plus(self, key: str, timeout_or_ping: str):
self.data.setdefault(key, {
"timeout": 0,
"ping": 0,
"ms": 0
})
self.data[key][timeout_or_ping] += 1
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment