#!/home/debian/Gestion_sondes/myenv/bin/python import os import subprocess import smtplib from email.mime.text import MIMEText from datetime import datetime from pathlib import Path BASE_DIR = Path('/home/debian/Gestion_sondes') ENV_FILE = BASE_DIR / '.env' def charger_env(path: Path) -> None: """Charge simplement les variables d'un fichier .env sans dépendance externe.""" if not path.exists(): return with path.open('r', encoding='utf-8') as f: for line in f: line = line.strip() if not line or line.startswith('#') or '=' not in line: continue key, value = line.split('=', 1) key = key.strip() value = value.strip().strip('"').strip("'") os.environ.setdefault(key, value) def lire_liste_mails(valeur: str) -> list[str]: return [mail.strip() for mail in valeur.split(',') if mail.strip()] charger_env(ENV_FILE) SMTP_HOST = os.getenv('SMTP_HOST', 'mail.mj91.fr') SMTP_PORT = int(os.getenv('SMTP_PORT', '465')) SMTP_SECURITY = os.getenv('SMTP_SECURITY', 'SSL').upper() SMTP_USER = os.getenv('SMTP_USER', 'services') SMTP_PASS = os.getenv('SMTP_PASS', '') MAIL_FROM = os.getenv('MAIL_FROM', 'services@domo91.fr') MAIL_TO = lire_liste_mails(os.getenv('MAIL_TO', 'services@domo91.fr')) heure_actuelle = datetime.now().strftime('%H:%M') etat_services = [] anomalies = [] try: output = subprocess.check_output( 'sudo /usr/bin/supervisorctl status', shell=True, text=True, stderr=subprocess.STDOUT, ) for line in output.splitlines(): parts = line.split() if len(parts) >= 2: nom, statut = parts[0], parts[1] etat_services.append(f'{nom} ➤ {statut}') if statut != 'RUNNING': anomalies.append(f'{nom} ➤ {statut}') except Exception as e: etat_services.append("❌ Impossible d'exécuter supervisorctl") anomalies.append(f'Erreur : {e}') # Déclenchement mail si anomalie ou rapport quotidien à 07:00 envoyer_mail = bool(anomalies) or heure_actuelle == '07:00' if envoyer_mail: sujet = "Rapport Supervisor - anomalie detectee" if anomalies else "Rapport quotidien Supervisor" intro = ( '🛑 Les services suivants ne sont pas en RUNNING :' if anomalies else '✅ Tous les services supervisés sont en RUNNING.' ) contenu = ( f'{intro}\n\n' f'Date contrôle : {datetime.now().strftime("%d/%m/%Y %H:%M:%S")}\n\n' + '\n'.join(etat_services) ) msg = MIMEText(contenu, _charset='utf-8') msg['Subject'] = sujet msg['From'] = MAIL_FROM msg['To'] = ', '.join(MAIL_TO) if not SMTP_PASS: print('Erreur envoi mail : SMTP_PASS est vide dans le fichier .env') else: try: if SMTP_SECURITY == 'SSL': with smtplib.SMTP_SSL(SMTP_HOST, SMTP_PORT) as server: server.login(SMTP_USER, SMTP_PASS) server.send_message(msg) elif SMTP_SECURITY == 'STARTTLS': with smtplib.SMTP(SMTP_HOST, SMTP_PORT) as server: server.ehlo() server.starttls() server.ehlo() server.login(SMTP_USER, SMTP_PASS) server.send_message(msg) else: with smtplib.SMTP(SMTP_HOST, SMTP_PORT) as server: server.login(SMTP_USER, SMTP_PASS) server.send_message(msg) print('📧 Mail envoyé.') except Exception as e: print(f'Erreur envoi mail : {e}') else: print("🕖 Aucun mail envoyé (tout est OK et ce n’est pas l’heure du rapport).")