监控系统资源情况并发送邮件告警
脚本如下
import psutil
import smtplib
from email.mime.text import MIMEText
CPU_THRESHOLD = 90
MEM_THRESHOLD = 80
SENDER = "8748789xx@qq.com"
RECIPIENT = "zpjxxx@163.com"
SMTP_SERVER = "smtp.qq.com"
SMTP_PORT = 587
SMTP_USERNAME = '8748789xx@qq.com'
SMTP_PASSWORD = 'xxxx'
def send_alert_email(subject, body):
"""发送警报邮件"""
msg = MIMEText(body)
msg['Subject'] = subject
msg['From'] = SENDER
msg['To'] = RECIPIENT
with smtplib.SMTP(SMTP_SERVER, SMTP_PORT) as server:
server.starttls()
server.login(SMTP_USERNAME, SMTP_PASSWORD)
server.send_message(msg)
def monitor_resources():
"""监控CPU和内存使用情况"""
cpu_percent = psutil.cpu_percent()
mem_percent = psutil.virtual_memory().percent
if cpu_percent > CPU_THRESHOLD:
subject = 'CPU使用率过高警报'
body = f'CPU使用率已超过{CPU_THRESHOLD}%,当前使用率为{cpu_percent}%'
send_alert_email(subject, body)
if mem_percent > MEM_THRESHOLD:
subject = '内存使用率过高警报'
body = f'内存使用率已超过{MEM_THRESHOLD}%,当前使用率为{mem_percent}%'
send_alert_email(subject, body)
if __name__ == '__main__':
monitor_resources()
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
上次更新: 2024/06/11, 23:05:26