DeaD_EyE icon

interface stats from /proc/net/dev

DeaD_EyE | PRO | 10/15/22 08:18:51 AM UTC | 0 ⭐ | 1178 👁️ | Never ⏰ | []
Python |

1.24 KB

|

None

|

0 👍

/

0 👎

from __future__ import annotations
from pathlib import Path
from typing import NamedTuple
 
 
DEV = Path("/proc/net/dev")
 
 
class ReceiveStats(NamedTuple):
    bytes: int
    packets: int
    errs: int
    drop: int
    fifo: int
    frame: int
    compressed: int
    multicast: int
 
 
class TransmitStats(NamedTuple):
    bytes: int
    packets: int
    errs: int
    drop: int
    fifo: int
    colls: int
    carrier: int
    compressed: int
 
 
class StatsResult(NamedTuple):
    interface: str
    receive: ReceiveStats
    transmit: TransmitStats
 
 
def interface_stats(interface: str) -> StatsResult | None:
    with DEV.open() as fd:
        # skip header
        for _ in range(2):
            next(fd)
 
        # read statistics
        for iface, *data in map(str.split, fd):
            iface = iface.removesuffix(":")
            if iface == interface:
                # convert all data to int
                data = tuple(map(int, data))
 
                # instanciate from data a NamedTuple
                receive = ReceiveStats(*data[0:8])
                transmit = TransmitStats(*data[8:])
                # return combined NamedTuple
                return StatsResult(iface, receive, transmit)
 

Comments

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

    0 B

    |

    👍

    /

    👎