# -*- coding: utf-8 -*-
import psutil
import time
import socket # 确保导入socket模块
def get_network_info():
# 获取所有网络接口信息
interfaces = psutil.net_if_addrs()
stats = psutil.net_io_counters(pernic=True)
for interface, addrs in interfaces.items():
print("\n接口: {}".format(interface))
# 打印IP地址
for addr in addrs:
if addr.family == socket.AF_INET: # 这里必须使用socket.AF_INET
print(" IP地址: {}".format(addr.address))
# 打印流量统计
if interface in stats:
io = stats[interface]
print(" 发送字节: {}".format(io.bytes_sent))
print(" 接收字节: {}".format(io.bytes_recv))
def monitor_network(interval=5):
try:
while True:
get_network_info()
time.sleep(interval)
except KeyboardInterrupt:
print("\n监控已停止")
if __name__ == "__main__":
monitor_network()
测试的环境:centos7.9+python3.6
输出效果: