Last active
January 2, 2023 19:14
-
-
Save bigntallmike/8ac8ff1990ecb38857f740ac03eadc89 to your computer and use it in GitHub Desktop.
Wrote a quick class to parse /proc/net/dev data
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/python3 -ttu | |
# | |
# Class to read and parse /proc/net/dev quickly and make the data available as a dictionary | |
# and/or json. | |
# | |
# Licensed: MIT. Just use it. Technically Copyright (C) 2022 Michael T. Babcock | |
from collections import OrderedDict | |
import re | |
class procnetdata: | |
__statsregexnamed = re.compile( | |
r"(?P<interface>\w+):\s+" | |
"(?P<rx_bytes>\d+)\s+" | |
"(?P<rx_packets>\d+)\s+" | |
"(?P<rx_errors>\d+)\s+" | |
"(?P<rx_drop>\d+)\s+" | |
"(?P<rx_fifo>\d+)\s+" | |
"(?P<rx_frame>\d+)\s+" | |
"(?P<rx_compressed>\d+)\s+" | |
"(?P<rx_multicast>\d+)\s+" | |
"(?P<tx_bytes>\d+)\s+" | |
"(?P<tx_packets>\d+)\s+" | |
"(?P<tx_errors>\d+)\s+" | |
"(?P<tx_dropped>\d+)\s+" | |
"(?P<tx_fifo>\d+)\s+" | |
"(?P<tx_colls>\d+)\s+" | |
"(?P<tx_carrier>\d+)\s+" | |
"(?P<tx_compressed>\d+)\s+" | |
) | |
def __init__(self): | |
self._data = OrderedDict() | |
# 5000 loops, best of 5: 85 usec per loop | |
def mapreaddict(self): | |
"""Read /proc/net/dev and parse it into an internal dictionary""" | |
with open("/proc/net/dev", "r") as procnetdev: | |
matched = map(self.__statsregexnamed.match, procnetdev) | |
for ifdata in (i.groupdict() for i in matched if i): | |
self._data[ifdata["interface"]] = ifdata | |
def __getitem__(self, key): | |
"""Make the data from /proc/net/dev available as a dictionary""" | |
return self._data[key] | |
def __repr__(self): | |
"""Return the parsed data as a json string""" | |
import json | |
return json.dumps(self._data, indent=4, sort_keys=True) | |
def __iter__(self): | |
"""Iterates over the names of interfaces""" | |
for entry in self._data: | |
yield entry | |
if __name__ == "__main__": | |
pndata = procnetdata() | |
pndata.mapreaddict() | |
print(pndata) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment