python-パブリックIPの発信帯域幅

Aug 19 2020

以下のコード行を使用して、centosボックスから送信された合計バイト数を確認しています

import psutil
psutil.net_io_counters().bytes_sent

パブリックIPのためだけにこれを実行したいと思います。つまり、パブリックIP専用の発信帯域幅を計算したいのです。

回答

kerasbaz Aug 20 2020 at 03:11
import ipaddress
import psutil

net = psutil.net_io_counters(pernic=True)

for name, interface in psutil.net_if_addrs().items():
    for address in interface:
        try:
            network = ipaddress.IPv4Network(f'{address.address}\{address.netmask}')
            if not network.is_private and not network.is_reserved:
                print(net[name].bytes_sent)
                break
        except ValueError as e:
            # these would be eg MAC addresses or similar
            pass