PythonでNICの統計情報を取得する

Pythonなコードから ethtool -S 相当のNIC統計情報を取得する必要に迫られたときどうするか。ただし ethtool コマンドの出力結果をパースする方法は使用しないものとする。

$ python -V
Python 3.6.5
$ uname -a
Linux laptop 4.16.12-200.fc27.x86_64 #1 SMP Fri May 25 21:10:16 UTC 2018 x86_64 x86_64 x86_64 GNU/Linux

gist.github.com

$ python ethtool.py wlp4s0
rx_packets: 421793
rx_bytes: 423497644
rx_duplicates: 4
rx_fragments: 421402
rx_dropped: 2008
tx_packets: 218510
tx_bytes: 60880710
tx_filtered: 0
tx_retry_failed: 0
tx_retries: 15806
sta_state: 4
txrate: 866700000
rxrate: 780000000
signal: 203
channel: 0

ざっくりした方針として ethtool.cのdo_gstats()を移植している。本来は ctypes.Structure を使うのが正しいのだとは思うが、可変長の要素 (たとえば struct ethtool_gstrings ) を綺麗に扱う方法が思い付かなかったので array.array で。