Advertisement
DeaD_EyE

interface stats from /proc/net/dev

Oct 15th, 2022
663
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.24 KB | None | 0 0
  1. from __future__ import annotations
  2. from pathlib import Path
  3. from typing import NamedTuple
  4.  
  5.  
  6. DEV = Path("/proc/net/dev")
  7.  
  8.  
  9. class ReceiveStats(NamedTuple):
  10.     bytes: int
  11.     packets: int
  12.     errs: int
  13.     drop: int
  14.     fifo: int
  15.     frame: int
  16.     compressed: int
  17.     multicast: int
  18.  
  19.  
  20. class TransmitStats(NamedTuple):
  21.     bytes: int
  22.     packets: int
  23.     errs: int
  24.     drop: int
  25.     fifo: int
  26.     colls: int
  27.     carrier: int
  28.     compressed: int
  29.  
  30.  
  31. class StatsResult(NamedTuple):
  32.     interface: str
  33.     receive: ReceiveStats
  34.     transmit: TransmitStats
  35.  
  36.  
  37. def interface_stats(interface: str) -> StatsResult | None:
  38.     with DEV.open() as fd:
  39.         # skip header
  40.         for _ in range(2):
  41.             next(fd)
  42.  
  43.         # read statistics
  44.         for iface, *data in map(str.split, fd):
  45.             iface = iface.removesuffix(":")
  46.             if iface == interface:
  47.                 # convert all data to int
  48.                 data = tuple(map(int, data))
  49.  
  50.                 # instanciate from data a NamedTuple
  51.                 receive = ReceiveStats(*data[0:8])
  52.                 transmit = TransmitStats(*data[8:])
  53.                 # return combined NamedTuple
  54.                 return StatsResult(iface, receive, transmit)
  55.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement