MAJ visualiseur logs
This commit is contained in:
2
.env
2
.env
@@ -3,7 +3,6 @@ DB_HOST=162.19.78.131
|
|||||||
DB_USER=sondes
|
DB_USER=sondes
|
||||||
DB_PASSWORD=TX.)-U1!zq5Axdk4
|
DB_PASSWORD=TX.)-U1!zq5Axdk4
|
||||||
DB_NAME=Sondes
|
DB_NAME=Sondes
|
||||||
VPS_PASSWORD=lpZwixbBUFtGY
|
|
||||||
|
|
||||||
# MQTT
|
# MQTT
|
||||||
MQTT_HOST=162.19.78.131
|
MQTT_HOST=162.19.78.131
|
||||||
@@ -11,7 +10,6 @@ MQTT_PORT=1883
|
|||||||
MQTT_USER=sondes
|
MQTT_USER=sondes
|
||||||
MQTT_PASS=3J@bjYP0
|
MQTT_PASS=3J@bjYP0
|
||||||
|
|
||||||
|
|
||||||
# paramètres mail
|
# paramètres mail
|
||||||
SMTP_HOST=smtp.mail.ovh.net
|
SMTP_HOST=smtp.mail.ovh.net
|
||||||
SMTP_PORT=465
|
SMTP_PORT=465
|
||||||
|
|||||||
@@ -1,164 +1,116 @@
|
|||||||
# visualiseur_logs.py
|
# visualiseur_logs.py
|
||||||
import os
|
# Dépendances: streamlit, paramiko
|
||||||
|
# pip install streamlit paramiko
|
||||||
|
|
||||||
|
import html
|
||||||
|
import time
|
||||||
from datetime import datetime
|
from datetime import datetime
|
||||||
import streamlit as st
|
import streamlit as st
|
||||||
|
|
||||||
# Dépendances SSH & .env
|
|
||||||
try:
|
try:
|
||||||
import paramiko
|
import paramiko
|
||||||
except ImportError:
|
except ImportError:
|
||||||
paramiko = None
|
paramiko = None
|
||||||
|
|
||||||
try:
|
|
||||||
from dotenv import load_dotenv
|
# =========================
|
||||||
except ImportError:
|
# CONFIG — À RENSEIGNER
|
||||||
load_dotenv = None
|
# =========================
|
||||||
|
VPS_HOST = "162.19.78.131" # ← mets ton IP/DNS
|
||||||
|
VPS_PORT = 22 # ← port SSH
|
||||||
|
VPS_USER = "debian" # ← utilisateur
|
||||||
|
VPS_PASSWORD = "lpZwixbBUFtGY" # ← mot de passe
|
||||||
|
VPS_LOG_DIR = "/home/debian/Gestion_sondes/Logs" # ← dossier des logs sur le VPS
|
||||||
|
|
||||||
|
|
||||||
# =========================
|
# =========================
|
||||||
# CONFIG & CHARGEMENT .ENV
|
# UI
|
||||||
# =========================
|
# =========================
|
||||||
st.set_page_config(page_title="Visualiseur de Logs (VPS, password)", layout="wide")
|
st.set_page_config(page_title="Visualiseur de Logs (VPS, password)", layout="wide")
|
||||||
st.title("🧾 Visualiseur de fichiers logs (VPS)")
|
st.title("🧾 Visualiseur de fichiers logs (VPS)")
|
||||||
|
st.caption(f"Cible : {VPS_USER}@{VPS_HOST}:{VPS_PORT} • Dossier logs : {VPS_LOG_DIR}")
|
||||||
|
|
||||||
# Chemins possibles du .env
|
if paramiko is None:
|
||||||
CANDIDATE_ENV = [
|
st.error("Paramiko n’est pas installé. Exécute : pip install paramiko")
|
||||||
"/home/debian/Gestion_sondes/.env",
|
st.stop()
|
||||||
os.path.join(os.path.expanduser("~"), "Gestion_sondes", ".env"),
|
|
||||||
".env",
|
|
||||||
]
|
|
||||||
ENV_LOADED_FROM = None
|
|
||||||
if load_dotenv:
|
|
||||||
for p in CANDIDATE_ENV:
|
|
||||||
if os.path.isfile(p):
|
|
||||||
load_dotenv(p)
|
|
||||||
ENV_LOADED_FROM = p
|
|
||||||
break
|
|
||||||
|
|
||||||
# Valeurs par défaut (surchageables par .env)
|
# Barre latérale : options d’affichage & refresh
|
||||||
VPS_HOST = os.getenv("VPS_HOST", "app.domo91.fr")
|
|
||||||
VPS_PORT = int(os.getenv("VPS_PORT", "22") or "22")
|
|
||||||
VPS_USER = os.getenv("VPS_USER", "debian")
|
|
||||||
VPS_PASSWORD = os.getenv("VPS_PASSWORD", "")
|
|
||||||
VPS_LOG_DIR = os.getenv("VPS_LOG_DIR", "/home/debian/Gestion_sondes/Logs")
|
|
||||||
|
|
||||||
|
|
||||||
# =========================
|
|
||||||
# BARRE LATÉRALE
|
|
||||||
# =========================
|
|
||||||
with st.sidebar:
|
with st.sidebar:
|
||||||
st.header("⚙️ Configuration")
|
st.header("⚙️ Options")
|
||||||
if not load_dotenv:
|
auto_refresh = st.toggle("🔄 Rafraîchissement auto", value=False, key="auto_refresh")
|
||||||
st.caption("Astuce : installe python-dotenv pour charger automatiquement un .env")
|
refresh_interval = st.slider("Intervalle (secondes)", 2, 60, 5, key="refresh_interval")
|
||||||
st.code("pip install python-dotenv", language="bash")
|
if st.button("Rafraîchir maintenant"):
|
||||||
st.caption(f".env chargé depuis : `{ENV_LOADED_FROM or 'non trouvé'}`")
|
st.rerun()
|
||||||
|
|
||||||
VPS_HOST = st.text_input("Hôte VPS", value=VPS_HOST)
|
|
||||||
VPS_PORT = st.number_input("Port", value=VPS_PORT, min_value=1, max_value=65535, step=1)
|
|
||||||
VPS_USER = st.text_input("Utilisateur", value=VPS_USER)
|
|
||||||
VPS_LOG_DIR = st.text_input("Dossier des logs (VPS)", value=VPS_LOG_DIR)
|
|
||||||
VPS_PASSWORD = st.text_input("Mot de passe (VPS)", value=VPS_PASSWORD, type="password")
|
|
||||||
|
|
||||||
st.markdown("---")
|
|
||||||
st.caption("Connexion par **mot de passe** uniquement (pas de clé).")
|
|
||||||
|
|
||||||
|
|
||||||
# =========================
|
# =========================
|
||||||
# FONCTIONS SSH (password)
|
# FONCTIONS SSH
|
||||||
# =========================
|
# =========================
|
||||||
def ssh_connect_password(host, port, user, password):
|
def ssh_connect_password(host, port, user, password):
|
||||||
"""Retourne un client SSH connecté (password)."""
|
"""Retourne un client SSH connecté (password)."""
|
||||||
if paramiko is None:
|
|
||||||
raise RuntimeError("Paramiko n’est pas installé. Fais : pip install paramiko")
|
|
||||||
|
|
||||||
ssh = paramiko.SSHClient()
|
ssh = paramiko.SSHClient()
|
||||||
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
|
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
|
||||||
ssh.connect(hostname=host, port=int(port), username=user, password=password, timeout=10)
|
ssh.connect(hostname=host, port=int(port), username=user, password=password, timeout=10)
|
||||||
return ssh
|
return ssh
|
||||||
|
|
||||||
|
|
||||||
def list_logs_over_ssh(ssh, log_dir):
|
def list_logs_over_ssh(ssh, log_dir):
|
||||||
"""
|
"""
|
||||||
Retourne une liste triée (par mtime desc) de dicts :
|
Liste les *.log du dossier (sans sous-dossiers), triés par mtime desc.
|
||||||
[{'name': 'f.log', 'mtime': 1726140001.0, 'size': 12345}, ...]
|
Retourne [{'name': 'f.log', 'mtime': 1234567890.0, 'size': 1024}, ...]
|
||||||
Utilise 'find' + 'printf' pour robustesse et performance.
|
|
||||||
"""
|
"""
|
||||||
# -maxdepth 1 : uniquement dans le dossier
|
cmd = (
|
||||||
# -type f -name "*.log" : fichiers .log
|
f"bash -lc \"find '{log_dir}' -maxdepth 1 -type f -name '*.log' "
|
||||||
# -printf "%T@ %s %f\n" : mtime_epoch size filename
|
f"-printf '%T@ %s %f\\n' 2>/dev/null | sort -nr\""
|
||||||
cmd = f"bash -lc \"find '{log_dir}' -maxdepth 1 -type f -name '*.log' -printf '%T@ %s %f\\n' 2>/dev/null | sort -nr\""
|
)
|
||||||
_, stdout, stderr = ssh.exec_command(cmd)
|
_, stdout, stderr = ssh.exec_command(cmd)
|
||||||
err = stderr.read().decode(errors="ignore").strip()
|
_ = stderr.read().decode(errors="ignore") # on ignore les warnings find
|
||||||
out = stdout.read().decode(errors="ignore")
|
out = stdout.read().decode(errors="ignore")
|
||||||
|
|
||||||
# Pas bloquant si 'find' écrit sur stderr pour des warnings, on ignore
|
items = []
|
||||||
logs = []
|
|
||||||
for line in out.splitlines():
|
for line in out.splitlines():
|
||||||
line = line.strip()
|
parts = line.strip().split(" ", 2)
|
||||||
if not line:
|
|
||||||
continue
|
|
||||||
parts = line.split(" ", 2)
|
|
||||||
if len(parts) < 3:
|
if len(parts) < 3:
|
||||||
continue
|
continue
|
||||||
try:
|
try:
|
||||||
mtime = float(parts[0])
|
mtime = float(parts[0]); size = int(parts[1]); name = parts[2]
|
||||||
size = int(parts[1])
|
items.append({"name": name, "mtime": mtime, "size": size})
|
||||||
name = parts[2]
|
|
||||||
logs.append({"name": name, "mtime": mtime, "size": size})
|
|
||||||
except Exception:
|
except Exception:
|
||||||
continue
|
continue
|
||||||
return logs
|
return items
|
||||||
|
|
||||||
|
|
||||||
def read_tail_over_ssh(ssh, remote_path, n_lines):
|
def read_tail_over_ssh(ssh, remote_path, n_lines):
|
||||||
"""
|
"""Lit les N dernières lignes via 'tail -n' (rapide sur gros logs)."""
|
||||||
Lit les N dernières lignes via 'tail -n' (rapide pour gros logs).
|
|
||||||
Retourne str (contenu brut).
|
|
||||||
"""
|
|
||||||
n = max(1, int(n_lines))
|
n = max(1, int(n_lines))
|
||||||
cmd = f"bash -lc \"tail -n {n} '{remote_path}'\""
|
cmd = f"bash -lc \"tail -n {n} '{remote_path}'\""
|
||||||
_, stdout, stderr = ssh.exec_command(cmd)
|
_, stdout, stderr = ssh.exec_command(cmd)
|
||||||
err = stderr.read().decode(errors="ignore")
|
err = stderr.read().decode(errors="ignore")
|
||||||
if err and "No such file" in err:
|
if "No such file" in err:
|
||||||
raise FileNotFoundError(err)
|
raise FileNotFoundError(err)
|
||||||
return stdout.read().decode(errors="ignore")
|
return stdout.read().decode(errors="ignore")
|
||||||
|
|
||||||
|
|
||||||
def backup_and_truncate_remote(ssh, remote_path):
|
def backup_and_truncate_remote(ssh, remote_path):
|
||||||
"""
|
"""Crée une sauvegarde horodatée .bak et tronque le fichier à 0 octet. Retourne le chemin .bak."""
|
||||||
Crée une sauvegarde horodatée .bak et tronque le fichier à 0 octet.
|
|
||||||
Retourne le chemin de la sauvegarde.
|
|
||||||
"""
|
|
||||||
ts = datetime.now().strftime("%Y%m%d-%H%M%S")
|
ts = datetime.now().strftime("%Y%m%d-%H%M%S")
|
||||||
bak = f"{remote_path}.{ts}.bak"
|
bak = f"{remote_path}.{ts}.bak"
|
||||||
# cp (backup) + truncate (ou redirection fallback)
|
|
||||||
cmd = (
|
cmd = (
|
||||||
f"bash -lc \"cp '{remote_path}' '{bak}' 2>/dev/null || true; "
|
f"bash -lc \"cp '{remote_path}' '{bak}' 2>/dev/null || true; "
|
||||||
f"truncate -s 0 '{remote_path}' 2>/dev/null || : > '{remote_path}'\""
|
f"truncate -s 0 '{remote_path}' 2>/dev/null || : > '{remote_path}'\""
|
||||||
)
|
)
|
||||||
_, stdout, stderr = ssh.exec_command(cmd)
|
_, out, err = ssh.exec_command(cmd)
|
||||||
_ = stdout.read()
|
_ = out.read()
|
||||||
err = stderr.read().decode(errors="ignore").strip()
|
e = err.read().decode(errors="ignore").strip()
|
||||||
# On tolère la plupart des messages ; on remonte seulement si 'No such file'
|
if "No such file" in e:
|
||||||
if "No such file" in err:
|
raise FileNotFoundError(e)
|
||||||
raise FileNotFoundError(err)
|
|
||||||
return bak
|
return bak
|
||||||
|
|
||||||
|
|
||||||
# =========================
|
# =========================
|
||||||
# CONTRÔLE DES CHAMPS AVANT CONNEXION
|
# CONNEXION & LISTE
|
||||||
# =========================
|
# =========================
|
||||||
if not VPS_HOST or not VPS_USER or not VPS_LOG_DIR:
|
if not all([VPS_HOST, VPS_USER, VPS_PASSWORD, VPS_LOG_DIR]):
|
||||||
st.error("Renseigne au minimum Hôte, Utilisateur et Dossier des logs.")
|
st.error("Complète les constantes en haut du fichier (hôte/utilisateur/mot de passe/dossier logs).")
|
||||||
st.stop()
|
|
||||||
if not VPS_PASSWORD:
|
|
||||||
st.error("Renseigne le mot de passe pour l’authentification.")
|
|
||||||
st.stop()
|
st.stop()
|
||||||
|
|
||||||
|
|
||||||
# =========================
|
|
||||||
# CONNEXION & LISTE DES LOGS
|
|
||||||
# =========================
|
|
||||||
try:
|
try:
|
||||||
ssh = ssh_connect_password(VPS_HOST, VPS_PORT, VPS_USER, VPS_PASSWORD)
|
ssh = ssh_connect_password(VPS_HOST, VPS_PORT, VPS_USER, VPS_PASSWORD)
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
@@ -177,37 +129,35 @@ if not logs:
|
|||||||
st.warning("Aucun fichier *.log trouvé dans ce dossier sur le VPS.")
|
st.warning("Aucun fichier *.log trouvé dans ce dossier sur le VPS.")
|
||||||
st.stop()
|
st.stop()
|
||||||
|
|
||||||
# Combobox des fichiers, triés par mtime desc
|
fichiers = [x["name"] for x in logs]
|
||||||
fichiers = [item["name"] for item in logs]
|
choix = st.selectbox("📂 Sélectionnez un fichier log :", fichiers, index=0)
|
||||||
choix = st.selectbox("📂 Sélectionnez un fichier log (VPS) :", fichiers, index=0)
|
|
||||||
log_info = next((x for x in logs if x["name"] == choix), logs[0])
|
log_info = next((x for x in logs if x["name"] == choix), logs[0])
|
||||||
log_path = f"{VPS_LOG_DIR.rstrip('/')}/{choix}"
|
log_path = f"{VPS_LOG_DIR.rstrip('/')}/{choix}"
|
||||||
|
|
||||||
# Infos de bandeau
|
|
||||||
mtime_dt = datetime.fromtimestamp(log_info["mtime"])
|
mtime_dt = datetime.fromtimestamp(log_info["mtime"])
|
||||||
st.caption(
|
st.caption(f"`{choix}` — Taille : {log_info['size']:,} o — Modifié : {mtime_dt:%Y-%m-%d %H:%M:%S}")
|
||||||
f"VPS {VPS_USER}@{VPS_HOST} • `{choix}` — "
|
|
||||||
f"Taille : {log_info['size']:,} octets — Modifié le : {mtime_dt:%Y-%m-%d %H:%M:%S}"
|
|
||||||
)
|
|
||||||
|
|
||||||
# =========================
|
# =========================
|
||||||
# OPTIONS D'AFFICHAGE
|
# OPTIONS & LECTURE
|
||||||
# =========================
|
# =========================
|
||||||
col1, col2 = st.columns([1, 1])
|
col1, col2, col3 = st.columns([1, 1, 1.2])
|
||||||
with col1:
|
with col1:
|
||||||
filtre_erreurs = st.checkbox(
|
filtre_erreurs = st.checkbox(
|
||||||
"🔍 Afficher uniquement les erreurs",
|
"🔍 Afficher uniquement les erreurs",
|
||||||
value=False,
|
value=False,
|
||||||
help="Filtre sur ERROR, ❌, Traceback, failed, exception"
|
help="Filtre sur ERROR, ❌, Traceback, failed, exception, critical, fatal"
|
||||||
)
|
)
|
||||||
with col2:
|
with col2:
|
||||||
nb_lignes = st.slider("📏 Nombre de lignes à afficher", 10, 5000, 300)
|
nb_lignes = st.slider("📏 Lignes à afficher", 10, 5000, 300)
|
||||||
|
with col3:
|
||||||
|
highlight = st.checkbox(
|
||||||
|
"🖍️ Surligner erreurs/avertissements",
|
||||||
|
value=True,
|
||||||
|
help="Met en évidence ERROR/CRITICAL/EXCEPTION (rouge) et WARN (jaune)"
|
||||||
|
)
|
||||||
|
|
||||||
# =========================
|
# Lecture (on prend une marge quand filtre actif)
|
||||||
# LECTURE DU CONTENU (tail)
|
|
||||||
# =========================
|
|
||||||
try:
|
try:
|
||||||
# Lis légèrement plus que demandé quand on filtre, pour avoir assez de matière
|
|
||||||
marge = 300 if filtre_erreurs else 0
|
marge = 300 if filtre_erreurs else 0
|
||||||
content = read_tail_over_ssh(ssh, log_path, nb_lignes + marge)
|
content = read_tail_over_ssh(ssh, log_path, nb_lignes + marge)
|
||||||
lignes = content.splitlines(keepends=True)
|
lignes = content.splitlines(keepends=True)
|
||||||
@@ -216,31 +166,50 @@ except Exception as e:
|
|||||||
st.error(f"Impossible de lire le fichier : {e}")
|
st.error(f"Impossible de lire le fichier : {e}")
|
||||||
st.stop()
|
st.stop()
|
||||||
|
|
||||||
# On peut fermer ici (les actions rouvriront une connexion fraîche)
|
# On peut fermer maintenant (les actions rouvriront une session propre)
|
||||||
ssh.close()
|
ssh.close()
|
||||||
|
|
||||||
# Filtre "erreurs"
|
# Filtrage
|
||||||
if filtre_erreurs:
|
if filtre_erreurs:
|
||||||
mots_cles = ["error", "❌", "traceback", "failed", "exception"]
|
err_keys = ["error", "traceback", "failed", "exception", "critical", "fatal"]
|
||||||
lignes = [l for l in lignes if any(m in l.lower() for m in mots_cles)]
|
lignes = [l for l in lignes if any(k in l.lower() for k in err_keys)]
|
||||||
|
|
||||||
# Affichage
|
|
||||||
dernieres = lignes[-nb_lignes:]
|
dernieres = lignes[-nb_lignes:]
|
||||||
st.text_area("📄 Contenu du fichier log :", "".join(dernieres), height=600)
|
|
||||||
|
# Surlignage
|
||||||
|
def colorize(lines):
|
||||||
|
out = []
|
||||||
|
for l in lines:
|
||||||
|
low = l.lower()
|
||||||
|
style = (
|
||||||
|
"font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, 'Liberation Mono', 'Courier New', monospace;"
|
||||||
|
"white-space: pre-wrap; margin: 0; padding: 2px 6px; border-radius: 4px;"
|
||||||
|
)
|
||||||
|
bg = None
|
||||||
|
if any(k in low for k in ["error", "traceback", "failed", "exception", "critical", "fatal", "❌"]):
|
||||||
|
bg = "#ffe6e6" # rouge clair
|
||||||
|
elif "warn" in low:
|
||||||
|
bg = "#fff8e1" # jaune clair
|
||||||
|
if bg:
|
||||||
|
style += f"background:{bg};"
|
||||||
|
out.append(f"<div style='{style}'>{html.escape(l)}</div>")
|
||||||
|
return "\n".join(out)
|
||||||
|
|
||||||
|
if highlight:
|
||||||
|
st.markdown(colorize(dernieres), unsafe_allow_html=True)
|
||||||
|
else:
|
||||||
|
st.text_area("📄 Contenu du fichier log :", "".join(dernieres), height=600)
|
||||||
|
|
||||||
st.divider()
|
st.divider()
|
||||||
|
|
||||||
# =========================
|
# =========================
|
||||||
# ACTIONS : BACKUP + VIDAGE
|
# ACTIONS (Backup + Vidage)
|
||||||
# =========================
|
# =========================
|
||||||
st.subheader("🧰 Actions sur ce fichier (VPS)")
|
st.subheader("🧰 Actions sur ce fichier (VPS)")
|
||||||
colA, colB, colC = st.columns([1, 1, 2])
|
colA, colB, colC = st.columns([1, 1, 2])
|
||||||
with colA:
|
with colA:
|
||||||
faire_backup = st.checkbox(
|
faire_backup = st.checkbox("Créer une copie .bak avant vidage", value=True,
|
||||||
"Créer une copie .bak avant vidage",
|
help="Copie horodatée à côté du fichier.")
|
||||||
value=True,
|
|
||||||
help="Copie horodatée placée à côté du fichier."
|
|
||||||
)
|
|
||||||
with colB:
|
with colB:
|
||||||
confirmation = st.checkbox("Je confirme vouloir vider", value=False)
|
confirmation = st.checkbox("Je confirme vouloir vider", value=False)
|
||||||
with colC:
|
with colC:
|
||||||
@@ -257,17 +226,73 @@ if vider:
|
|||||||
bak_path = backup_and_truncate_remote(ssh2, log_path)
|
bak_path = backup_and_truncate_remote(ssh2, log_path)
|
||||||
st.info(f"📦 Copie de sauvegarde créée : `{bak_path}`")
|
st.info(f"📦 Copie de sauvegarde créée : `{bak_path}`")
|
||||||
else:
|
else:
|
||||||
# Troncature seule
|
|
||||||
cmd = f"bash -lc \"truncate -s 0 '{log_path}' 2>/dev/null || : > '{log_path}'\""
|
cmd = f"bash -lc \"truncate -s 0 '{log_path}' 2>/dev/null || : > '{log_path}'\""
|
||||||
_, out, err = ssh2.exec_command(cmd)
|
_, out, err = ssh2.exec_command(cmd)
|
||||||
_ = out.read(); _ = err.read()
|
_ = out.read(); _ = err.read()
|
||||||
|
|
||||||
st.success("✅ Fichier vidé avec succès.")
|
st.success("✅ Fichier vidé avec succès.")
|
||||||
st.rerun()
|
st.rerun()
|
||||||
|
|
||||||
except PermissionError:
|
except PermissionError:
|
||||||
st.error("⛔ Permission refusée. Vérifie les droits sur le fichier/dossier.")
|
st.error("⛔ Permission refusée. Vérifie les droits sur le fichier/dossier.")
|
||||||
except FileNotFoundError as e:
|
except FileNotFoundError as e:
|
||||||
st.error(f"📁 Fichier ou dossier introuvable : {e}")
|
st.error(f"📁 Fichier/dossier introuvable : {e}")
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
st.error(f"❌ Échec du vidage : {e}")
|
st.error(f"❌ Échec du vidage : {e}")
|
||||||
|
|
||||||
|
# =========================
|
||||||
|
# PURGE DE PLUSIEURS LOGS
|
||||||
|
# =========================
|
||||||
|
st.subheader("🗑️ Purge de plusieurs logs (VPS)")
|
||||||
|
|
||||||
|
# On reliste tous les logs disponibles
|
||||||
|
try:
|
||||||
|
ssh3 = ssh_connect_password(VPS_HOST, VPS_PORT, VPS_USER, VPS_PASSWORD)
|
||||||
|
all_logs = list_logs_over_ssh(ssh3, VPS_LOG_DIR)
|
||||||
|
ssh3.close()
|
||||||
|
except Exception as e:
|
||||||
|
all_logs = []
|
||||||
|
st.error(f"Impossible de relister les logs : {e}")
|
||||||
|
|
||||||
|
if all_logs:
|
||||||
|
age_jours = st.number_input("Supprimer les fichiers plus vieux que (jours)", 1, 365, 7)
|
||||||
|
now = time.time()
|
||||||
|
candidats = [x for x in all_logs if (now - x["mtime"]) / 86400 >= age_jours]
|
||||||
|
|
||||||
|
if not candidats:
|
||||||
|
st.info("Aucun fichier ne correspond au filtre d'âge.")
|
||||||
|
else:
|
||||||
|
st.write(f"📂 {len(candidats)} fichier(s) plus vieux que {age_jours} jours trouvé(s).")
|
||||||
|
|
||||||
|
selection = []
|
||||||
|
for x in candidats:
|
||||||
|
label = f'{x["name"]} — {x["size"]/1024:.1f} Ko — {datetime.fromtimestamp(x["mtime"]).strftime("%Y-%m-%d %H:%M")}'
|
||||||
|
if st.checkbox(label, key=f"purge_{x['name']}"):
|
||||||
|
selection.append(x["name"])
|
||||||
|
|
||||||
|
if selection:
|
||||||
|
st.warning(f"{len(selection)} fichier(s) sélectionné(s) pour suppression définitive.")
|
||||||
|
confirm = st.checkbox("Je confirme la suppression définitive", key="confirm_purge")
|
||||||
|
if st.button("❌ Supprimer les fichiers sélectionnés", type="primary", disabled=not confirm):
|
||||||
|
try:
|
||||||
|
ssh4 = ssh_connect_password(VPS_HOST, VPS_PORT, VPS_USER, VPS_PASSWORD)
|
||||||
|
for fname in selection:
|
||||||
|
remote_path = f"{VPS_LOG_DIR.rstrip('/')}/{fname}"
|
||||||
|
cmd = f"bash -lc \"rm -f '{remote_path}'\""
|
||||||
|
_, out, err = ssh4.exec_command(cmd)
|
||||||
|
_ = out.read(); _ = err.read()
|
||||||
|
ssh4.close()
|
||||||
|
st.success(f"✅ {len(selection)} fichier(s) supprimé(s).")
|
||||||
|
st.rerun()
|
||||||
|
except Exception as e:
|
||||||
|
st.error(f"Erreur lors de la suppression : {e}")
|
||||||
|
else:
|
||||||
|
st.info("Aucun log trouvé pour la purge.")
|
||||||
|
|
||||||
|
# =========================
|
||||||
|
# AUTO-REFRESH (fin de script)
|
||||||
|
# =========================
|
||||||
|
if auto_refresh:
|
||||||
|
# Affiche une petite info et relance la page après X secondes
|
||||||
|
st.caption(f"🔄 Rafraîchissement auto activé — Prochaine mise à jour dans {refresh_interval} s…")
|
||||||
|
time.sleep(refresh_interval)
|
||||||
|
st.rerun()
|
||||||
|
|||||||
@@ -1,37 +1,80 @@
|
|||||||
#!/bin/bash
|
#!/bin/bash
|
||||||
|
set -Eeuo pipefail
|
||||||
|
|
||||||
# Variables
|
DATE="$(date +'%Y-%m-%d_%H-%M')"
|
||||||
DATE=$(date +'%Y-%m-%d_%H-%M')
|
|
||||||
BACKUP_DIR="/home/debian/backup"
|
BACKUP_DIR="/home/debian/backup"
|
||||||
LOG_DIR="/home/debian/Gestion_sondes/Logs"
|
LOG_DIR="/home/debian/Gestion_sondes/Logs"
|
||||||
|
mkdir -p "$LOG_DIR" "$BACKUP_DIR"
|
||||||
|
|
||||||
LOG_FILE="$LOG_DIR/backup_$DATE.log"
|
LOG_FILE="$LOG_DIR/backup_$DATE.log"
|
||||||
exec > "$LOG_FILE" 2>&1
|
exec > >(tee -a "$LOG_FILE") 2>&1
|
||||||
|
|
||||||
|
# Verrou anti-doublon (facultatif mais prudent)
|
||||||
|
exec 9>/tmp/backup_mysql.lock
|
||||||
|
flock -n 9 || { echo "🔒 Un autre backup est en cours. Abandon."; exit 1; }
|
||||||
|
|
||||||
BACKUP_FILE="$BACKUP_DIR/mysql_backup_$DATE.sql"
|
BACKUP_FILE="$BACKUP_DIR/mysql_backup_$DATE.sql"
|
||||||
NAS_HOST="mon-nas" # défini dans /home/debian/.ssh/config
|
|
||||||
MYSQL_USER="root"
|
|
||||||
MYSQL_PASSWORD="$%kavYKeb1EY3Vl136O&o"
|
|
||||||
NAS_DIR="/volume1/nfs/vps_gra" # chemin sur le NAS
|
|
||||||
|
|
||||||
# Création du dossier local si besoin
|
# Cible NAS (alias dans ~/.ssh/config)
|
||||||
mkdir -p "$BACKUP_DIR"
|
NAS_HOST="DSM920"
|
||||||
|
NAS_DIR="/volume1/VPS/Gravelines"
|
||||||
|
SSH_OPTS="-F /home/debian/.ssh/config -o BatchMode=yes -o StrictHostKeyChecking=accept-new"
|
||||||
|
|
||||||
echo "🔷 Sauvegarde des bases MySQL..."
|
# Chemin credentials MySQL (recommandé)
|
||||||
if mysqldump -u "$MYSQL_USER" -p"$MYSQL_PASSWORD" --all-databases > "$BACKUP_FILE"; then
|
MYSQL_DEFAULTS="/home/debian/.my.cnf"
|
||||||
echo "✅ Sauvegarde locale terminée : $BACKUP_FILE"
|
|
||||||
else
|
# PATH minimal pour cron
|
||||||
echo "❌ Erreur lors de la sauvegarde MySQL"
|
export PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
|
||||||
exit 1
|
|
||||||
|
echo "🔷 Démarrage $(date '+%F %T') sur $(hostname -s)"
|
||||||
|
echo "🔷 Dossier local : $BACKUP_DIR"
|
||||||
|
echo "🔷 Dossier NAS : $NAS_DIR (hôte $NAS_HOST)"
|
||||||
|
|
||||||
|
# 1) Pré-check SSH & droits écriture NAS
|
||||||
|
echo "🔷 Test SSH NAS…"
|
||||||
|
if ! ssh "SSH_OPTS "$NAS_HOST" "mkdir -p '$NAS_DIR' && test -w '$NAS_DIR' && echo __SSH_OK__"; then
|
||||||
|
echo "❌ Impossible d écrire sur $NAS_HOST:$NAS_DIR (clé SSH ? user ? droits ? SSH NAS activé ?)"
|
||||||
|
exit 20
|
||||||
fi
|
fi
|
||||||
|
|
||||||
echo "🔷 Envoi de la sauvegarde vers le NAS..."
|
# 2) Dump MySQL (format .sql, options sûres)
|
||||||
if rsync -av -e ssh "$BACKUP_FILE" "$NAS_HOST:$NAS_DIR/"; then
|
echo "🔷 Dump MySQL…"
|
||||||
echo "✅ Sauvegarde transférée sur le NAS : $NAS_HOST"
|
if [[ -f "$MYSQL_DEFAULTS" ]]; then
|
||||||
|
DUMP="mysqldump --defaults-file=$MYSQL_DEFAULTS --all-databases --single-transaction --quick --lock-tables=false --routines --events --triggers"
|
||||||
else
|
else
|
||||||
echo "❌ Échec du transfert vers le NAS"
|
DUMP="mysqldump --all-databases --single-transaction --quick --lock-tables=false --routines --events --triggers"
|
||||||
exit 1
|
|
||||||
fi
|
fi
|
||||||
|
|
||||||
echo "🔷 Nettoyage des sauvegardes locales de plus de 7 jours..."
|
# Baisse de priorité pour ne pas gêner la prod
|
||||||
find "$BACKUP_DIR" -type f -name "*.sql" -mtime +7 -exec rm -f {} \;
|
IONICE="$(command -v ionice >/dev/null 2>&1 && echo 'ionice -c2 -n7' || true)"
|
||||||
|
NICE="$(command -v nice >/dev/null 2>&1 && echo 'nice -n 10' || true)"
|
||||||
|
|
||||||
echo "🎉 Opération terminée avec succès !"
|
bash -c "$IONICE $NICE $DUMP > '$BACKUP_FILE'"
|
||||||
|
|
||||||
|
# Sanity check
|
||||||
|
if [[ ! -s "$BACKUP_FILE" ]]; then
|
||||||
|
echo "❌ Fichier de backup vide : $BACKUP_FILE"
|
||||||
|
exit 21
|
||||||
|
fi
|
||||||
|
LOCAL_SIZE=$(stat -c%s "$BACKUP_FILE" 2>/dev/null || wc -c < "$BACKUP_FILE")
|
||||||
|
echo "✅ Dump OK : $BACKUP_FILE ($LOCAL_SIZE octets)"
|
||||||
|
|
||||||
|
# 3) Transfert → NAS
|
||||||
|
echo "🔷 Transfert vers le NAS…"
|
||||||
|
rsync -av --partial -e "ssh $SSH_OPTS" "$BACKUP_FILE" "$NAS_HOST:$NAS_DIR/"
|
||||||
|
|
||||||
|
# 4) Vérification taille distante = locale (robuste BusyBox)
|
||||||
|
BASENAME="$(basename "$BACKUP_FILE")"
|
||||||
|
REMOTE_SIZE=$(ssh $SSH_OPTS "$NAS_HOST" "wc -c < '$NAS_DIR/$BASENAME'" || echo 0)
|
||||||
|
if [[ "$REMOTE_SIZE" != "$LOCAL_SIZE" ]]; then
|
||||||
|
echo "❌ Taille différente après transfert (local=$LOCAL_SIZE, distant=$REMOTE_SIZE)"
|
||||||
|
exit 22
|
||||||
|
fi
|
||||||
|
echo "✅ Transfert OK → $NAS_HOST:$NAS_DIR/$BASENAME"
|
||||||
|
|
||||||
|
# 5) Rotation locale (garder 14 fichiers)
|
||||||
|
echo "🔷 Rotation locale (garder 14 fichiers)…"
|
||||||
|
ls -1t "$BACKUP_DIR"/mysql_backup_*.sql 2>/dev/null | tail -n +15 | xargs -r rm -f
|
||||||
|
|
||||||
|
|
||||||
|
echo "🏁 Terminé $(date '+%F %T')"
|
||||||
|
|||||||
Reference in New Issue
Block a user