Refonte sauvegarde MariaDB NAS => VPS2

This commit is contained in:
2026-06-08 10:44:38 +02:00
parent a49f20cd0b
commit 87e2bc7b51
6 changed files with 289 additions and 26 deletions

View File

@@ -0,0 +1,13 @@
import mysql.connector
conn = mysql.connector.connect(
host="10.9.0.1",
port=3306,
user="Michel",
password="wuP^wu&6xjx61bh*kjS^",
database="Sondes"
)
print("Connexion MariaDB OK via WireGuard")
conn.close()

View File

@@ -1,45 +1,115 @@
#!/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
heure_actuelle = datetime.now().strftime("%H:%M")
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)
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}")
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}")
anomalies.append(f'Erreur : {e}')
# Déclenchement mail si anomalie ou à 07:00
envoyer_mail = bool(anomalies) or heure_actuelle == "07:00"
# Déclenchement mail si anomalie ou rapport quotidien à 07:00
envoyer_mail = bool(anomalies) or heure_actuelle == '07:00'
if envoyer_mail:
sujet = "⚠️ Alerte Supervisor" 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" + "\n".join(etat_services)
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.'
)
msg = MIMEText(contenu)
msg["Subject"] = sujet
msg["From"] = "supervisor@domo91.fr"
msg["To"] = "services@domo91.fr"
contenu = (
f'{intro}\n\n'
f'Date contrôle : {datetime.now().strftime("%d/%m/%Y %H:%M:%S")}\n\n'
+ '\n'.join(etat_services)
)
try:
with smtplib.SMTP_SSL("smtp.mail.ovh.net", 465) as server:
server.login("services@domo91.fr", "VHq3278YA#sGV*bh#mR")
server.sendmail(msg["From"], [msg["To"]], msg.as_string())
print("📧 Mail envoyé.")
except Exception as e:
print(f"Erreur envoi mail : {e}")
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 nest pas lheure du rapport).")