你可以使用Python的psutil库获取系统CPU、内存和磁盘空间的使用情况,使用matplotlib库绘制折线图,使用smtplib库发送邮件报警。
以下是一个简单的示例代码:
```python
import psutil
import matplotlib.pyplot as plt
import datetime
import time
import smtplib
from email.mime.text import MIMEText
from email.header import Header
# 发送邮件报警
def send_email_alert(subject, content):
mail_host = "smtp.xxx.com" # 邮箱服务器地址
mail_user = "your_email" # 邮箱账号
mail_pass = "your_password" # 邮箱密码
sender = 'your_email' # 发件人邮箱
receivers = ['receiver_email'] # 收件人邮箱列表
message = MIMEText(content, 'plain', 'utf-8')
message['From'] = Header("System Monitor", 'utf-8')
message['To'] = Header("Admin", 'utf-8')
message['Subject'] = Header(subject, 'utf-8')
try:
smtpObj = smtplib.SMTP_SSL(mail_host, 465)
smtpObj.login(mail_user, mail_pass)
smtpObj.sendmail(sender, receivers, message.as_string())
smtpObj.quit()
print("邮件发送成功")
except smtplib.SMTPException as e:
print("Error: 无法发送邮件")
print(e)
# 获取CPU、内存和磁盘空间使用情况
def get_system_info():
cpu_percent = psutil.cpu_percent()
mem_percent = psutil.virtual_memory().percent
disk_percent = psutil.disk_usage('/').percent
return cpu_percent, mem_percent, disk_percent
# 绘制折线图
def plot_line_chart(x, y, title, xlabel, ylabel):
fig, ax = plt.subplots()
ax.plot(x, y)
ax.set(xlabel=xlabel, ylabel=ylabel, title=title)
ax.grid()
plt.show()
# 监控近一年系统使用情况
def monitor_system():
# 初始化数据
cpu_data = []
mem_data = []
disk_data = []
time_data = []
# 监控近一年系统使用情况
for i in range(365):
cpu_percent, mem_percent, disk_percent = get_system_info()
cpu_data.append(cpu_percent)
mem_data.append(mem_percent)
disk_data.append(disk_percent)
time_data.append(datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
time.sleep(3600) # 每隔一个小时获取一次数据
# 绘制折线图
plot_line_chart(time_data, cpu_data, 'CPU Usage', 'Time', 'CPU Usage (%)')
plot_line_chart(time_data, mem_data, 'Memory Usage', 'Time', 'Memory Usage (%)')
plot_line_chart(time_data, disk_data, 'Disk Usage', 'Time', 'Disk Usage (%)')
# 发送邮件报警
if max(cpu_data) >= 90:
subject = 'CPU usage is too high!'
content = 'The CPU usage is {}% at {}.'.format(max(cpu_data), time_data[cpu_data.index(max(cpu_data))])
send_email_alert(subject, content)
if max(mem_data) >= 90:
subject = 'Memory usage is too high!'
content = 'The memory usage is {}% at {}.'.format(max(mem_data), time_data[mem_data.index(max(mem_data))])
send_email_alert(subject, content)
if max(disk_data) >= 90:
subject = 'Disk usage is too high!'
content = 'The disk usage is {}% at {}.'.format(max(disk_data), time_data[disk_data.index(max(disk_data))])
send_email_alert(subject, content)
if __name__ == '__main__':
monitor_system()
```
这个示例代码会每隔一个小时获取一次系统CPU、内存和磁盘空间的使用情况,并绘制近一年的折线图。如果某个指标的最大值超过90%,则会发送邮件报警。你需要将`your_email`和`your_password`替换成实际的邮箱账号和密码,将`mail_host`替换成实际的邮箱服务器地址,将`receiver_email`替换成实际的收件人邮箱。