DeaD_EyE icon

get rx and tx bytes from network interface on linux

DeaD_EyE | PRO | 07/14/22 03:42:04 PM UTC | 0 ⭐ | 1401 👁️ | Never ⏰ | []
Python |

1 KB

|

None

|

0 👍

/

0 👎

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")

Comments

  •  icon
    01/01/70 12:00:00 AM UTC
    Plain Text |

    0 B

    |

    👍

    /

    👎