python监控网卡流量
时间: 2023-10-12 17:11:10 浏览: 90
以下是使用Python监控网卡流量的示例代码:
```python
import psutil
import time
def bytes_to_readable(bytes):
suffixes = ['B', 'KB', 'MB', 'GB']
index = 0
while bytes >= 1024 and index < len(suffixes)-1:
bytes /= 1024.0
index += 1
return f"{bytes:.2f} {suffixes[index]}"
def monitor_network():
last_bytes_sent = 0
last_bytes_recv = 0
while True:
net_io_counters = psutil.net_io_counters()
bytes_sent = net_io_counters.bytes_sent
bytes_recv = net_io_counters.bytes_recv
if last_bytes_sent and last_bytes_recv:
bytes_sent_diff = bytes_sent - last_bytes_sent
bytes_recv_diff = bytes_recv - last_bytes_recv
print(f"Bytes sent: {bytes_to_readable(bytes_sent_diff)}/s")
print(f"Bytes received: {bytes_to_readable(bytes_recv_diff)}/s")
last_bytes_sent = bytes_sent
last_bytes_recv = bytes_recv
time.sleep(1)
if __name__ == '__main__':
monitor_network()
```
此代码使用psutil库来获取系统网络输入输出的字节数,并计算速率。它使用时间间隔为1秒的无限循环来监视流量。
阅读全文