当 CPU 使用率超过 80%、内存使用超过 90% 或磁盘空间不足 10GB 时,向指定的邮箱发送警报邮件。帮我写个列子
时间: 2024-03-06 10:47:31 浏览: 21
好的,以下是一个 Python 代码示例,用于监测系统 CPU、内存和磁盘使用情况,并在达到预设阈值时发送警报邮件。
```python
import psutil
import smtplib
from email.mime.text import MIMEText
# 设置阈值
cpu_threshold = 80
mem_threshold = 90
disk_threshold = 10
# 获取系统信息
cpu_usage = psutil.cpu_percent()
mem_usage = psutil.virtual_memory().percent
disk_usage = psutil.disk_usage('/').free / 1024 / 1024 / 1024 # 单位:GB
# 检查是否超过阈值
if cpu_usage > cpu_threshold or mem_usage > mem_threshold or disk_usage < disk_threshold:
# 发送警报邮件
smtp_server = 'smtp.example.com' # 设置 SMTP 服务器地址
smtp_port = 587 # 设置 SMTP 服务器端口
smtp_user = 'your_username' # 设置 SMTP 服务器用户名
smtp_password = 'your_password' # 设置 SMTP 服务器密码
sender = 'sender@example.com' # 设置发送人邮箱
receivers = ['receiver1@example.com', 'receiver2@example.com'] # 设置接收人邮箱列表
message = MIMEText('警报!系统资源使用率超过阈值!') # 设置邮件内容
message['From'] = sender
message['To'] = ','.join(receivers)
message['Subject'] = '系统资源使用率警报'
try:
smtp_obj = smtplib.SMTP(smtp_server, smtp_port)
smtp_obj.starttls()
smtp_obj.login(smtp_user, smtp_password)
smtp_obj.sendmail(sender, receivers, message.as_string())
print('邮件发送成功')
except Exception as e:
print('邮件发送失败:', e)
finally:
smtp_obj.quit()
```
请注意,这只是一个简单的示例代码,实际情况中,你需要根据自己的需求进行修改和完善。另外,为了确保代码的安全性和可靠性,建议将敏感信息(如 SMTP 服务器地址、用户名、密码等)存储在配置文件或环境变量中,而不是直接写入代码中。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![application/x-zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)