Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import json
- from subprocess import check_output
- from pathlib import Path
- def to_unit(value: int | str | bytes) -> str:
- if isinstance(value, (str, bytes)):
- value = int(value)
- for unit in ("B", "KiB", "MiB", "GiB", "TiB"):
- if value < 1024:
- break
- value /= 1024
- return f"{value:.3f} {unit}"
- def get_stats_mib(interface: str) -> tuple[str, str]:
- data = json.loads(check_output(["ip", "-j", "-s", "link", "show", "dev", interface]))
- stats = data[0]["stats64"]
- return to_unit(stats["rx"]["bytes"]), to_unit(stats["tx"]["bytes"])
- def get_stats_mib_py(interface: str) -> tuple[str, str]:
- if_path = Path("/sys/class/net") / interface / "statistics"
- if not if_path.exists():
- raise ValueError(f"Interface {interface} does not exist.")
- rx = to_unit(if_path.joinpath("rx_bytes").read_bytes())
- tx = to_unit(if_path.joinpath("tx_bytes").read_bytes())
- return rx, tx
- get_stats_mib_py("eno1")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement