import time
from app.utils_ydf import LogManager
logger = LogManager('network_monitor').get_logger_and_add_handlers(log_filename='network_monitor.log')
logger_templete7 = LogManager('network_monitor2').get_logger_and_add_handlers(log_filename='network_monitor.log', formatter_template=7, do_not_use_color_handler=True)
speed_down = []
speed_up = []
speed_name = []
speed_up_1 = []
speed_down_1 = []
while True:
i = open('/proc/net/dev', 'r').readlines()
for p in i:
p = p.split()
if p[1].isdigit() and p[1] != '0':
index = 0
for i in range(len(speed_name)):
if p[0] == speed_name[i]:
index = i
break
if p[0] in speed_name:
pass
else:
speed_name.append(p[0])
speed_down_1.append(p[1])
speed_up_1.append(p[9])
speed_down.append(0)
speed_up.append(0)
break
speed_down[index] = float(int(p[1]) - int(speed_down_1[index])) / 1000
speed_up[index] = float(int(p[9]) - int(speed_up_1[index])) / 1000
speed_down_1[index] = p[1]
speed_up_1[index] = p[9]
for i in range(len(speed_name)):
# if speed_name[i] == 'eno1:':
if 'eno1:' in speed_name[i]: # 只打印此网卡
logger_templete7.debug(f"网卡:{speed_name[i]}")
msg1 = f"上行: {speed_up[i]}"
msg2 = f'下行: {speed_down[i]}'
if speed_up[i] < 100:
logger.debug(msg1)
elif 100 <= speed_up[i] < 200:
logger.info(msg1)
elif 200 <= speed_up[i] < 300:
logger.warning(msg1)
elif 300 <= speed_up[i] < 400:
logger.error(msg1)
elif 400 <= speed_up[i]:
logger.critical(msg1)
if speed_down[i] < 100:
logger.debug(msg2)
elif 100 <= speed_down[i] < 200:
logger.info(msg2)
elif 200 <= speed_down[i] < 300:
logger.warning(msg2)
elif 300 <= speed_down[i] < 400:
logger.error(msg2)
elif 400 <= speed_down[i]:
logger.critical(msg2)
time.sleep(1)
网上找的,亲测可用。
![](https://img2018.cnblogs.com/blog/1108990/201810/1108990-20181030141644862-1094253117.png)