用python实现下面的功能,实时监控所有进程的信息,一旦某个进程的CPU,RAM,磁盘,网络IO中某个指标占用率超出给定阈值,就显示报警信息,显示该进程的具体信息,以及它发生异常的时间
时间: 2024-04-15 14:27:21 浏览: 8
实现实时监控所有进程的信息并进行异常报警,可以使用psutil库结合一些条件判断和定时任务。下面是一个简单的示例代码:
```python
import psutil
import time
# 设置阈值(示例阈值为50%)
cpu_threshold = 50
ram_threshold = 50
disk_threshold = 50
net_threshold = 50
while True:
for proc in psutil.process_iter(['pid', 'name', 'cpu_percent', 'memory_percent']):
pid = proc.info['pid']
name = proc.info['name']
cpu_percent = proc.info['cpu_percent']
ram_percent = proc.info['memory_percent']
# 获取磁盘IO信息
disk_io = psutil.disk_io_counters(perdisk=True).get('C:')
disk_percent = disk_io.percent if disk_io else 0
# 获取网络IO信息
net_io = psutil.net_io_counters()
net_percent = net_io.percent if net_io else 0
# 判断是否超过阈值
if cpu_percent > cpu_threshold or ram_percent > ram_threshold or disk_percent > disk_threshold or net_percent > net_threshold:
current_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
print(f"异常报警:进程ID {pid}, 进程名称 {name}")
print(f"异常发生时间:{current_time}")
print(f"CPU 占用率:{cpu_percent}%")
print(f"内存 占用率:{ram_percent}%")
print(f"磁盘 占用率:{disk_percent}%")
print(f"网络 IO 占用率:{net_percent}%")
print("---------------------------------")
# 每隔一段时间进行检测(示例为5秒)
time.sleep(5)
```
这段代码会不断地遍历所有进程,并获取每个进程的CPU占用率、内存占用率、磁盘占用率和网络IO占用率。如果某个指标超过了阈值,就会打印异常报警信息,包括具体进程信息和异常发生的时间。
你可以根据需要修改阈值和检测间隔。此外,你还可以根据实际需求扩展代码,例如记录异常信息到日志文件、发送邮件或短信通知等。
请注意,该示例代码仅提供了基本的监控和报警功能,实际应用中还需要考虑更多的细节和安全性。