Outils pour utilisateurs

Outils du site


scripts

Différences

Ci-dessous, les différences entre deux révisions de la page.

Lien vers cette vue comparative

Les deux révisions précédentesRévision précédente
Prochaine révision
Révision précédente
scripts [2025/05/28 13:57] – [MYSQL DATABASE BACKUP] huracanscripts [2025/12/04 14:31] (Version actuelle) – [PYTHON] huracan
Ligne 1: Ligne 1:
 ====== SCRIPTS ====== ====== SCRIPTS ======
 +
 +
 +
  
  
Ligne 8: Ligne 11:
  
 ---- ----
 +
 +
 +===== PYTHON =====
 +
 +
 +Script pour commandes multithread sur plusieurs switchs
 +
 + #!/usr/bin/env python3
 + from concurrent.futures import ThreadPoolExecutor, as_completed
 + from datetime import datetime
 + from getpass import getpass
 + import threading
 + from pathlib import Path
 + import os
 + import socket
 + from netmiko import ConnectHandler
 +  
 + SWITCH_FILE = "switches.txt"
 + MAX_WORKERS = 20
 +  
 + print_lock = threading.Lock()
 +  
 +  
 + def safe_print(*a, **kw):
 + with print_lock:
 + print(*a, **kw, flush=True)
 +  
 +  
 + def load_hosts(path):
 + p = Path(path)
 + if not p.exists():
 + return []
 + return [x.strip() for x in p.read_text().splitlines() if x.strip()]
 +  
 +  
 + # --------- AJOUT : TEST SSH AVANT CONNEXION -----------
 + def test_ssh_port(host, port=22, timeout=2):
 + try:
 + with socket.create_connection((host, port), timeout=timeout):
 + return True
 + except:
 + return False
 + # -------------------------------------------------------
 +  
 +  
 + def run_on_switch(host, username, password, commands):
 + result = {
 + "host": host,
 + "success": False,
 + "error": None,
 + "lines": [],
 + "start": datetime.now(),
 + "end": None,
 + }
 +  
 + # --- Test SSH avant toute connexion ---
 + if not test_ssh_port(host):
 + result["error"] = "SSH inaccessible (port 22 fermé / host down)"
 + result["end"] = datetime.now()
 + return result
 +  
 + try:
 + device = {
 + "device_type": "cisco_ios",
 + "host": host,
 + "username": username,
 + "password": password,
 + }
 +  
 + conn = ConnectHandler(**device)
 +  
 + except Exception as e:
 + result["error"] = f"SSH ERROR : {e}"
 + result["end"] = datetime.now()
 + return result
 +  
 + try:
 + conn.send_command("terminal length 0")
 +  
 + for cmd in commands:
 + out = conn.send_command(cmd, read_timeout=20)
 + for line in out.splitlines():
 + safe_print(f"[{host}] {line}")
 + result["lines"].append(line)
 +  
 + result["success"] = True
 +  
 + except Exception as e:
 + result["error"] = f"COMMAND ERROR : {e}"
 +  
 + finally:
 + conn.disconnect()
 + result["end"] = datetime.now()
 +  
 + return result
 +  
 +  
 + def choose_switches(hosts):
 + while True:
 + safe_print("\n====== SÉLECTION DES SWITCHES ======")
 + for i, h in enumerate(hosts, 1):
 + safe_print(f"{i}) {h}")
 +  
 + safe_print("\nOptions :")
 + safe_print("  X    -> numéro d’un switch")
 + safe_print("  1,3  -> plusieurs switchs")
 + safe_print("  all  -> tous les switches")
 + safe_print("  back -> revenir")
 + safe_print("====================================")
 +  
 + choice = input("Votre sélection : ").strip().lower()
 +  
 + if choice == "back":
 + return None
 +  
 + if choice == "all":
 + return hosts
 +  
 + try:
 + indices = [int(x.strip()) for x in choice.split(",")]
 + selected = [hosts[i - 1] for i in indices if 1 <= i <= len(hosts)]
 + if selected:
 + return selected
 + except:
 + pass
 +  
 + safe_print("Sélection invalide.")
 +  
 +  
 + def main():
 + hosts = load_hosts(SWITCH_FILE)
 + if not hosts:
 + safe_print(f"Erreur : fichier {SWITCH_FILE} introuvable ou vide.")
 + return
 +  
 + safe_print(f"{len(hosts)} switches chargés.")
 +  
 + username = input("Identifiant SSH : ").strip()
 + password = getpass("Mot de passe SSH : ")
 +  
 + current_selection = hosts  # par défaut : tous
 +  
 + while True:
 + safe_print("\n====== MENU PRINCIPAL ======")
 + safe_print("Switches sélectionnés :")
 + for h in current_selection:
 + safe_print(f"  - {h}")
 +  
 + safe_print("\nOptions :")
 + safe_print("  cmd   -> taper des commandes")
 + safe_print("  sel   -> changer la sélection")
 + safe_print("  clear -> effacer l'écran")
 + safe_print("  exit  -> quitter")
 + safe_print("============================")
 +  
 + choice = input("> ").strip().lower()
 +  
 + if choice == "exit":
 + return
 +  
 + if choice == "clear":
 + os.system("cls" if os.name == "nt" else "clear")
 + continue
 +  
 + if choice == "sel":
 + new_sel = choose_switches(hosts)
 + if new_sel:
 + current_selection = new_sel
 + continue
 +  
 + if choice == "cmd":
 + safe_print("Entrez vos commandes (ligne vide pour lancer l'exécution).")
 + commands = []
 +  
 + while True:
 + cmd = input("> ").strip()
 + if cmd == "":
 + if commands:
 + break
 + else:
 + continue
 + commands.append(cmd)
 +  
 + safe_print("\n====== EXÉCUTION ======\n")
 +  
 + start_all = datetime.now()
 +  
 + results = []
 + with ThreadPoolExecutor(max_workers=min(MAX_WORKERS, len(current_selection))) as pool:
 + future_map = {
 + pool.submit(run_on_switch, h, username, password, commands): h
 + for h in current_selection
 + }
 +  
 + for f in as_completed(future_map):
 + results.append(f.result())
 +  
 + # --- Résumé synthétique ---
 + safe_print("\n======= RÉSUMÉ =======")
 + for r in results:
 + host = r["host"]
 + status = "OK" if r["success"] else "ERREUR"
 + lines = len(r["lines"])
 + dur = (r["end"] - r["start"]).total_seconds()
 + safe_print(f"- {host}: {status} | lignes: {lines} | durée: {dur:.1f}s")
 + if r["error"]:
 + safe_print(f"    -> {r['error']}")
 +  
 + total = (datetime.now() - start_all).total_seconds()
 + safe_print(f"Durée totale : {total:.1f}s")
 + safe_print("=======================\n")
 +  
 +  
 + if __name__ == "__main__":
 + main()
 +
 +
 +
 +
 +----
 +
 +
  
 ===== WINDOWS ===== ===== WINDOWS =====
Ligne 14: Ligne 239:
 ---- ----
  
 +==== CONVERSION M4A EN FLAC AVEC FFMPEG ====
 +
 +🪟 Sur Windows (PowerShell ou CMD) :
 +
 +Dans le dossier contenant les .m4a exécuter :
 +
 +  #for %a in (*.m4a) do ffmpeg -i "%a" -c:a flac -map_metadata 0 "%~na.flac"
 +
 +
 +----
  
  
Ligne 1113: Ligne 1348:
   #echo `test $machin = 'truct'`   #echo `test $machin = 'truct'`
  
 +
 +----
 +
 +==== CONVERSION M4A EN FLAC AVEC FFMPEG ====
 +
 +Dans le dossier contenant les .m4a, exécuter :
 +
 +🐧 Sur Linux (terminal bash) :
 +
 +  #for f in *.m4a; do ffmpeg -i "$f" -c:a flac -map_metadata 0 "${f%.m4a}.flac"; done
  
 ---- ----
Ligne 1283: Ligne 1528:
  
  
 +=== Step 1: Creating MySQL Backup Script ===
 +
 +First, let’s create a simple Bash script that will handle the backup process.
 +
 +  nano backup_mysql.sh
 +
 +Copy and paste the following script into the backup_mysql.sh file:
 +
 +  #!/bin/bash
 +  
 +  # MySQL Credentials
 +  MYSQL_USER="your_mysql_username"
 +  MYSQL_PASS="your_mysql_password"
 +  MYSQL_HOST="localhost"
 +  
 +  # Backup Directory (ensure this directory exists)
 +  BACKUP_DIR="/path/to/your/backup/directory"
 +  
 +  # Email settings
 +  EMAIL_TO="you@example.com"
 +  EMAIL_SUBJECT="MySQL Backup Report - $(date +"%Y-%m-%d %H:%M:%S")"
 +  EMAIL_BODY=""
 +  
 +  # Get current date to append to backup filename
 +  DATE=$(date +"%Y-%m-%d_%H-%M-%S")
 +  
 +  # Databases to back up (list the names of the databases you want to back up)
 +  DATABASES=("db1" "db2" "db3")
 +  
 +  # Loop through each database and back it up
 +  for DB in "${DATABASES[@]}"; do
 +      BACKUP_FILE="$BACKUP_DIR/$DB_$DATE.sql"
 +      
 +      echo "Backing up database $DB to $BACKUP_FILE..."
 +      
 +      # Perform the backup using mysqldump
 +      mysqldump -u $MYSQL_USER -p$MYSQL_PASS -h $MYSQL_HOST $DB > $BACKUP_FILE
 +      
 +      # Check if the backup was successful
 +      if [ $? -eq 0 ]; then
 +          echo "Backup of $DB completed successfully!"
 +      else
 +          echo "Backup of $DB failed!"
 +      fi
 +  done
 +  
 +  # Clean up backups older than 30 days (optional)
 +  find $BACKUP_DIR -type f -name "*.sql" -mtime +30 -exec rm -f {} \;
 +  
 +  # Send email alert
 +  echo -e "$EMAIL_BODY" | mail -s "$EMAIL_SUBJECT" "$EMAIL_TO"
 +
 +What Does This Script Do?
 +
 +  * MySQL Credentials: You need to provide your MySQL username, password, and host (usually localhost).
 +  * Backup Directory: This is where your backups will be stored. Make sure this directory exists on your system.
 +  * Timestamped Backup: The script creates backups with a timestamp (e.g., 2025-04-28_12-30-00.sql) to avoid overwriting old backups.
 +  * Databases to Back Up: In the DATABASES array, list the names of the databases you want to back up. You can add or remove databases as needed.
 +  * Backup Command: The script uses mysqldump to create backups of your databases.
 +  * Old Backup Cleanup: The script also deletes backups older than 30 days (you can adjust this time as needed).
 +  * Email Alerts: After running the backup, the script sends an email with the results – whether each database backup succeeded or failed.
 +
 +**//Sync Backup to Remote Server (Optional but Recommended)//**
 +
 +After your local backup is created, it’s a smart move to sync it to a remote server for extra safety, which ensures your backups survive even if your main server crashes.
 +
 +Here’s the rsync command you can add to the end of your backup script:
 +
 +  # Sync backup to remote server (optional but recommended)
 +  
 +  SSH_KEY="/path/to/your/private/key.pem"           # Path to your SSH private key
 +  REMOTE_USER="your_remote_user"                    # Remote server username
 +  REMOTE_HOST="your.remote.server.com"              # Remote server address
 +  REMOTE_DIR="/path/on/remote/server"               # Target directory on remote server
 +  
 +  rsync -avz \
 +    -e "ssh -i $SSH_KEY -o StrictHostKeyChecking=no" \
 +    --delete-after \
 +    "$BACKUP_DIR/" \
 +    "$REMOTE_USER@$REMOTE_HOST:$REMOTE_DIR/"
 +
 +Make sure the remote server is reachable, and the destination directory exists with proper write permissions.
 +
 +Once you’ve saved your script, make it executable by running chmod command:
 +
 +  chmod +x backup_mysql.sh
 +
 +=== Step 2: Testing MySQL Backup Script ===
 +
 +Before setting up the Cron job, it’s a good idea to test the script manually to make sure everything is working as expected.
 +
 +  ./backup_mysql.sh
 +
 +Check your backup directory to ensure the backups are created successfully. If everything looks good, proceed to the next step.
 +
 +=== Step 3: Automating MySQL Backups with Cron Jobs ===
 +
 +Now that we have the backup script, the next step is to automate it by using Cron, a tool that runs commands at scheduled times.
 +
 +  crontab -e
 +
 +Add a Cron job to run the backup script automatically. For example, to run the script every day at 2 AM, add the following line:
 +
 +  0 2 * * * /bin/bash /path/to/your/backup_mysql.sh
 +
 +Here’s how the Cron schedule works:
 +
 +  * 0: The minute (0th minute).
 +  * 2: The hour (2 AM).
 +  * *: Every day of the month.
 +  * *: Every month.
 +  * *: Every day of the week.
 +
 +To verify that your Cron job is running, you can check the system logs or temporarily set the script to run at a closer time to see if it works.
 +
 +  grep CRON /var/log/syslog
 +
 +**//Additional Considerations//**
 +
 +  * Security: Storing your MySQL password in the script is convenient but not secure. For better security, you can store your credentials in a .my.cnf file in your home directory and configure the script to read from there.
 +  * Backup Location: Make sure that the backup directory has enough space for your backups. If you’re running multiple backups, it’s a good idea to set up a separate storage location (like an external hard drive or cloud storage).
 +  * Backup Frequency: Depending on how often your data changes, you might want to adjust the Cron job schedule. For example, you could run the backup every hour, every week, or only on certain days.
  
scripts.1748433454.txt.gz · Dernière modification : 2025/05/28 13:57 de huracan

DokuWiki Appliance - Powered by TurnKey Linux