前言
最近服务器有几次被安全狗断网,没找到好的解决方法。就先写了个Python程序监控网络状态,断网5分钟强制重启服务器的脚步。
代码
import psutil
import socket
import time
import os
import datetime
def check_internet_connection():
try:
socket.create_connection(("www.baidu.com", 80))
return True
except OSError:
return False
def saveLog():
# 获取当前时间
current_time = datetime.datetime.now()
savedate = current_time.strftime("%Y-%m-%d %H:%M:%S").replace(" ", "-").replace(":", "-")
# 打开日志文件,准备写入数据
with open(f"log_{savedate}.txt", "a") as file:
file.write(f"Server data snapshot at: {current_time}\n")
# 记录 CPU 使用率、内存情况和磁盘占用情况
cpu_percent = psutil.cpu_percent()
file.write(f"CPU 使用率: {cpu_percent}%\n")
memory = psutil.virtual_memory()
file.write(f"内存占用情况: {memory.percent}%\n")
disk_usage = psutil.disk_usage("/")
file.write(f"根目录磁盘占用情况: {disk_usage.percent}%\n")
# 记录网络连接数
connections = psutil.net_connections()
file.write(f"网络连接数: {len(connections)}\n")
def run():
# saveLog()
count = 0
while True:
if not check_internet_connection():
count += 1
if count >= 20:
saveLog()
print("连续断网 5 分钟, 准备重启服务器...")
os.system("shutdown /r /f /t 0")
break
print("当前断网次数: ", count)
else:
print("服务器状态正常")
count = 0
time.sleep(15) # 每隔5秒检查一次
if __name__ == "__main__":
run()
标签:count,监控,Python,percent,write,psutil,file,import,服务器 From: https://blog.csdn.net/roc_wei_chen/article/details/140286006