近日,某WIN服务器CPU老是100%卡死不动,导致云服务的健康状态检查总是有一项不通过,服务器无法使用,无法远程登录,也就无法看到是哪个进程占用了资源,本来想用WIN自带的资源监视器,但是懒得去配置,就做了一个小脚本,自动收集CPU占用超过80%的进程,万一卡死了下次登录还可以通过收集的记录看到是哪个进程导致的.
# -*- coding: utf-8 -*-
# @Protject_Name : pythontest
# @File : CPU大于80时将占用最高的进程写入文件.py
# @
import psutil
import datetime
import time
def get_high_cpu_process():
while True:
# 获取系统的 CPU 利用率
cpu_percent = psutil.cpu_percent(interval=1)
if cpu_percent > 80:
# 获取所有非空闲进程信息
processes = [proc for proc in psutil.process_iter(['pid', 'name', 'cpu_percent'])
if proc.info['cpu_percent'] is not None and proc.info['pid'] != 0]
if processes:
# 获取 CPU 利用率最高的非空闲进程
high_cpu_process = max(processes, key=lambda x: x.info['cpu_percent'])
# 获取当前时间
current_time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
# 将信息写入文本文件
with open("high_cpu_processes.txt", "a") as file:
file.write(f"{current_time}: CPU Percent: {cpu_percent}% - Process ID: {high_cpu_process.info['pid']} - Process Name: {high_cpu_process.info['name']}\n")
# 每隔一段时间检测一次
time.sleep(1) # 休眠1秒,可以根据需要调整休眠时间
if __name__ == "__main__":
get_high_cpu_process()
本章结束~ifan