Advertisement
DeaD_EyE

get rx and tx bytes from network interface on linux

Jul 14th, 2022
959
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.00 KB | None | 0 0
  1. import json
  2. from subprocess import check_output
  3. from pathlib import Path
  4.  
  5.  
  6. def to_unit(value: int | str | bytes) -> str:
  7.     if isinstance(value, (str, bytes)):
  8.         value = int(value)
  9.        
  10.     for unit in ("B", "KiB", "MiB", "GiB", "TiB"):
  11.         if value < 1024:
  12.             break
  13.         value /= 1024
  14.            
  15.     return f"{value:.3f} {unit}"
  16.  
  17.  
  18. def get_stats_mib(interface: str) -> tuple[str, str]:
  19.     data = json.loads(check_output(["ip", "-j", "-s", "link", "show", "dev", interface]))
  20.     stats = data[0]["stats64"]
  21.     return to_unit(stats["rx"]["bytes"]), to_unit(stats["tx"]["bytes"])
  22.  
  23.  
  24. def get_stats_mib_py(interface: str) -> tuple[str, str]:
  25.     if_path = Path("/sys/class/net") / interface / "statistics"
  26.     if not if_path.exists():
  27.         raise ValueError(f"Interface {interface} does not exist.")
  28.     rx = to_unit(if_path.joinpath("rx_bytes").read_bytes())
  29.     tx = to_unit(if_path.joinpath("tx_bytes").read_bytes())
  30.  
  31.     return rx, tx
  32.  
  33.  
  34. get_stats_mib_py("eno1")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement