import psutil
import logging
import smtplib
from email.mime.text import MIMEText
from datetime import datetime
import time
# 配置日志记录
logging.basicConfig(filename='/var/log/sys_monitor.log', level=logging.INFO,
format='%(asctime)s - %(levelname)s - %(message)s')
# 邮件通知函数
def send_email(subject, body, to_email):
from_email = 'your-email@example.com'
password = 'your-email-password'
msg = MIMEText(body)
msg['Subject'] = subject
msg['From'] = from_email
msg['To'] = to_email
with smtplib.SMTP('smtp.example.com', 587) as server:
server.starttls()
server.login(from_email, password)
server.sendmail(from_email, to_email, msg.as_string())
# 资源监控函数
def check_system_resources():
# 获取CPU和内存使用情况
cpu_usage = psutil.cpu_percent(interval=1)
memory_info = psutil.virtual_memory()
memory_usage = memory_info.percent
# 记录日志
logging.info(f'CPU Usage: {cpu_usage}%')
logging.info(f'Memory Usage: {memory_usage}%')
# 检查内存使用情况并发送通知
if memory_usage > 80: # 阈值可调整
subject = 'High Memory Usage Alert'
body = (f'High memory usage detected!\n\n'
f'CPU Usage: {cpu_usage}%\n'
f'Memory Usage: {memory_usage}%\n')
send_email(subject, body, 'admin@example.com')
# 主程序
if __name__ == "__main__":
while True:
check_system_resources()
time.sleep(60) # 每60秒检查一次
import psutil
import logging
import smtplib
from email.mime.text import MIMEText
from datetime import datetime
import time
# 配置日志记录
logging.basicConfig(filename='/var/log/sys_monitor.log', level=logging.INFO,
format='%(asctime)s - %(levelname)s - %(message)s')
# 邮件通知函数
def send_email(subject, body, to_email):
from_email = 'your-email@example.com'
password = 'your-email-password'
msg = MIMEText(body)
msg['Subject'] = subject
msg['From'] = from_email
msg['To'] = to_email
with smtplib.SMTP('smtp.example.com', 587) as server:
server.starttls()
server.login(from_email, password)
server.sendmail(from_email, to_email, msg.as_string())
# 资源监控函数
def check_system_resources():
# 获取CPU和内存使用情况
cpu_usage = psutil.cpu_percent(interval=1)
memory_info = psutil.virtual_memory()
memory_usage = memory_info.percent
# 记录日志
logging.info(f'CPU Usage: {cpu_usage}%')
logging.info(f'Memory Usage: {memory_usage}%')
# 检查内存使用情况并发送通知
if memory_usage > 80: # 阈值可调整
subject = 'High Memory Usage Alert'
body = (f'High memory usage detected!\n\n'
f'CPU Usage: {cpu_usage}%\n'
f'Memory Usage: {memory_usage}%\n')
send_email(subject, body, 'admin@example.com')
# 主程序
if __name__ == "__main__":
while True:
check_system_resources()
time.sleep(60) # 每60秒检查一次