task/test.py

65 lines
1.9 KiB
Python
Raw Permalink Normal View History

2025-02-23 18:54:44 +00:00
import smtplib
from email.mime.text import MIMEText
from email.utils import formatdate
import psutil # для получения метрик системы
import time
# Конфигурация SMTP
SMTP_SERVER = "smtp.gmail.com"
SMTP_PORT = 587
SMTP_USER = "your-email@gmail.com"
SMTP_PASSWORD = "your-password"
EMAIL_FROM = "your-email@gmail.com"
EMAIL_TO = "admin@example.com"
def monitor_resources():
"""Проверка метрик системы"""
alerts = []
# Пример: проверка загрузки CPU
cpu_percent = psutil.cpu_percent(interval=1)
if cpu_percent > 80:
alerts.append(f"High CPU usage: {cpu_percent}%")
# Пример: проверка свободной памяти
mem = psutil.virtual_memory()
if mem.percent > 80:
alerts.append(f"High Memory usage: {mem.percent}%")
# Пример: проверка дискового пространства
disk = psutil.disk_usage('/')
if disk.percent > 90:
alerts.append(f"Low disk space: {disk.percent}%")
return alerts
def send_email(subject, message):
"""Отправка email через SMTP"""
msg = MIMEText(message)
msg['Subject'] = subject
msg['From'] = EMAIL_FROM
msg['To'] = EMAIL_TO
msg['Date'] = formatdate(localtime=True)
try:
with smtplib.SMTP(SMTP_SERVER, SMTP_PORT) as server:
server.starttls() # Шифрование TLS
server.login(SMTP_USER, SMTP_PASSWORD)
server.sendmail(EMAIL_FROM, EMAIL_TO, msg.as_string())
print("Alert email sent!")
except Exception as e:
print(f"Failed to send email: {str(e)}")
if __name__ == "__main__":
while True:
alerts = monitor_resources()
if alerts:
subject = "[ALERT] System Issues Detected"
message = "\n".join(alerts)
send_email(subject, message)
time.sleep(60) # Проверка каждую минуту