[cat monitor2.py
#!/usr/bin/env python
#coding=UTF-8
import datetime
import socket
import psutil
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
# 全局变量
current_time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S") # 当前时间
server_ip = socket.gethostbyname(socket.gethostname()) # 服务器IP
# 监控CPU资源使用率
def check_cpu_usage():
cpu_usage = psutil.cpu_percent(interval=1)
if cpu_usage > 80:
send_email("CPU资源使用率过高", "当前CPU资源使用率为 {}%".format(cpu_usage))
# 监控内存资源使用率
def check_memory_usage():
memory = psutil.virtual_memory()
memory_usage = memory.percent
if memory_usage > 80:
send_email("内存资源使用率过高", "当前内存资源使用率为 {}%".format(memory_usage))
# 监控磁盘资源使用率
def check_disk_usage():
partitions = psutil.disk_partitions()
for partition in partitions:
disk_usage = psutil.disk_usage(partition.mountpoint).percent
if disk_usage > 80:
send_email("磁盘资源使用率过高", "磁盘 {} 的使用率为 {}%".format(partition.mountpoint, disk_usage))
# 发送邮件
def send_email(subject, message):
email_from = "" # 发件人邮箱
#email_to = "" # 收件人邮箱
email_to = [""] # 收件人邮箱
smtp_server = "smtp.exmail.qq.com" # SMTP服务器地址
smtp_port = 587 # SMTP服务器端口号
smtp_username = "" # SMTP服务器用户名
smtp_password = "" # SMTP服务器密码
# 构造邮件内容
message_with_info = """\
当前时间:{}
服务器IP:{}
告警内容:{}
""".format(current_time, server_ip, message)
#subject_with_aliyun = "[阿里云][{}][当前时间:{}][服务器IP:{}][告警内容:{}]".format(subject,current_time,server_ip,message)
subject_with_aliyun = "[阿里云][{}]".format(subject)
#msg = MIMEMultipart()
#msg = MIMEText(message, "plain")
msg = MIMEText(message_with_info, "plain", "utf-8") # 使用utf-8编码
msg["From"] = email_from
#msg["To"] = email_to
msg["To"] = ','.join(email_to)
#msg["Subject"] = subject
msg["Subject"] = subject_with_aliyun
#msg.attach(MIMEText(message, "plain"))
try:
smtp_obj = smtplib.SMTP(smtp_server, smtp_port)
smtp_obj.starttls()
smtp_obj.login(smtp_username, smtp_password)
smtp_obj.sendmail(email_from, email_to, msg.as_string())
smtp_obj.quit()
print("邮件发送成功")
except smtplib.SMTPException as e:
print("邮件发送失败:", e)
# 主程序
if __name__ == "__main__":
check_cpu_usage()
check_memory_usage()
check_disk_usage()