#!/usr/bin/env python3 import requests from xml.etree import ElementTree from sys import argv ROUTER_IP = "192.168.0.1" def b2B(num_of_bytes, start=-1): if type(num_of_bytes) not in (float, int): num_of_bytes = float(num_of_bytes) opts, i = "KMGTP", start while num_of_bytes > 1000: num_of_bytes = num_of_bytes / 1000 i += 1 return "{:.2f}{}B".format(num_of_bytes, opts[i]) def hms(s): m,s = divmod(s,60) h,m = divmod(m,60) d,h = divmod(h,24) y,d = divmod(d,365) return y,d,h,m,s def camel2sp(word): return ''.join(map(lambda x: x if x.islower() else " "+x, word)) i = requests.get("http://{}/html/home.html".format(ROUTER_IP)) d = requests.get("http://{}/api/monitoring/traffic-statistics".format(ROUTER_IP), headers={"Cookie": i.headers["Set-Cookie"]}).text if len(argv) > 1 and argv[1] == "-v": print(d) d = ElementTree.fromstring(d) for e in d: if e.tag in ["CurrentConnectTime", "TotalConnectTime"]: out = "{}: {}".format(camel2sp(e.tag), ":".join(str(x).zfill(2) for x in hms(int(e.text)) if x)) elif e.tag in ["CurrentUpload", "CurrentDownload", "TotalUpload", "TotalDownload"]: out = "{}: {}".format(camel2sp(e.tag), b2B(e.text)) elif e.tag in ["CurrentUploadRate", "CurrentDownloadRate"]: out = "{}: {}/s".format(camel2sp(e.tag), b2B(float(e.text), 0)) else: continue print(out.strip())