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/12/04 14:21] – [WINDOWS] huracanscripts [2025/12/04 14:31] (Version actuelle) – [PYTHON] huracan
Ligne 7: Ligne 7:
  
  
-----+
  
  
Ligne 18: Ligne 18:
 Script pour commandes multithread sur plusieurs switchs Script pour commandes multithread sur plusieurs switchs
  
-#!/usr/bin/env python3 + #!/usr/bin/env python3 
-from concurrent.futures import ThreadPoolExecutor, as_completed + from concurrent.futures import ThreadPoolExecutor, as_completed 
-from datetime import datetime + from datetime import datetime 
-from getpass import getpass + from getpass import getpass 
-import threading + import threading 
-from pathlib import Path + from pathlib import Path 
-import os + import os 
-import socket + import socket 
-from netmiko import ConnectHandler + from netmiko import ConnectHandler 
- +   
-SWITCH_FILE = "switches.txt" + SWITCH_FILE = "switches.txt" 
-MAX_WORKERS = 20 + MAX_WORKERS = 20 
- +   
-print_lock = threading.Lock() + print_lock = threading.Lock() 
- +   
- +   
-def safe_print(*a, **kw): + def safe_print(*a, **kw): 
-    with print_lock: + with print_lock: 
-        print(*a, **kw, flush=True) + print(*a, **kw, flush=True) 
- +   
- +   
-def load_hosts(path): + def load_hosts(path): 
-    p = Path(path) + p = Path(path) 
-    if not p.exists(): + if not p.exists(): 
-        return [] + return [] 
-    return [x.strip() for x in p.read_text().splitlines() if x.strip()] + return [x.strip() for x in p.read_text().splitlines() if x.strip()] 
- +   
- +   
-# --------- AJOUT : TEST SSH AVANT CONNEXION ----------- + # --------- AJOUT : TEST SSH AVANT CONNEXION ----------- 
-def test_ssh_port(host, port=22, timeout=2): + def test_ssh_port(host, port=22, timeout=2): 
-    try: + try: 
-        with socket.create_connection((host, port), timeout=timeout): + with socket.create_connection((host, port), timeout=timeout): 
-            return True + return True 
-    except: + except: 
-        return False + return False 
-# ------------------------------------------------------- + # ------------------------------------------------------- 
- +   
- +   
-def run_on_switch(host, username, password, commands): + def run_on_switch(host, username, password, commands): 
-    result = { + result = { 
-        "host": host, + "host": host, 
-        "success": False, + "success": False, 
-        "error": None, + "error": None, 
-        "lines": [], + "lines": [], 
-        "start": datetime.now(), + "start": datetime.now(), 
-        "end": None, + "end": None, 
-    +
- +   
-    # --- Test SSH avant toute connexion --- + # --- Test SSH avant toute connexion --- 
-    if not test_ssh_port(host): + if not test_ssh_port(host): 
-        result["error"] = "SSH inaccessible (port 22 fermé / host down)" + result["error"] = "SSH inaccessible (port 22 fermé / host down)" 
-        result["end"] = datetime.now() + result["end"] = datetime.now() 
-        return result + return result 
- +   
-    try: + try: 
-        device = { + device = { 
-            "device_type": "cisco_ios", + "device_type": "cisco_ios", 
-            "host": host, + "host": host, 
-            "username": username, + "username": username, 
-            "password": password, + "password": password, 
-        +
- +   
-        conn = ConnectHandler(**device) + conn = ConnectHandler(**device) 
- +   
-    except Exception as e: + except Exception as e: 
-        result["error"] = f"SSH ERROR : {e}" + result["error"] = f"SSH ERROR : {e}" 
-        result["end"] = datetime.now() + result["end"] = datetime.now() 
-        return result + return result 
- +   
-    try: + try: 
-        conn.send_command("terminal length 0") + conn.send_command("terminal length 0") 
- +   
-        for cmd in commands: + for cmd in commands: 
-            out = conn.send_command(cmd, read_timeout=20) + out = conn.send_command(cmd, read_timeout=20) 
-            for line in out.splitlines(): + for line in out.splitlines(): 
-                safe_print(f"[{host}] {line}"+ safe_print(f"[{host}] {line}"
-                result["lines"].append(line) + result["lines"].append(line) 
- +   
-        result["success"] = True + result["success"] = True 
- +   
-    except Exception as e: + except Exception as e: 
-        result["error"] = f"COMMAND ERROR : {e}" + result["error"] = f"COMMAND ERROR : {e}" 
- +   
-    finally: + finally: 
-        conn.disconnect() + conn.disconnect() 
-        result["end"] = datetime.now() + result["end"] = datetime.now() 
- +   
-    return result + return result 
- +   
- +   
-def choose_switches(hosts): + def choose_switches(hosts): 
-    while True: + while True: 
-        safe_print("\n====== SÉLECTION DES SWITCHES ======"+ safe_print("\n====== SÉLECTION DES SWITCHES ======"
-        for i, h in enumerate(hosts, 1): + for i, h in enumerate(hosts, 1): 
-            safe_print(f"{i}) {h}"+ safe_print(f"{i}) {h}"
- +   
-        safe_print("\nOptions :") + safe_print("\nOptions :") 
-        safe_print("  X    -> numéro d’un switch"+ safe_print("  X    -> numéro d’un switch"
-        safe_print("  1,3  -> plusieurs switchs"+ safe_print("  1,3  -> plusieurs switchs"
-        safe_print("  all  -> tous les switches"+ safe_print("  all  -> tous les switches"
-        safe_print("  back -> revenir"+ safe_print("  back -> revenir"
-        safe_print("===================================="+ safe_print("===================================="
- +   
-        choice = input("Votre sélection : ").strip().lower() + choice = input("Votre sélection : ").strip().lower() 
- +   
-        if choice == "back": + if choice == "back": 
-            return None + return None 
- +   
-        if choice == "all": + if choice == "all": 
-            return hosts + return hosts 
- +   
-        try: + try: 
-            indices = [int(x.strip()) for x in choice.split(",")] + indices = [int(x.strip()) for x in choice.split(",")] 
-            selected = [hosts[i - 1] for i in indices if 1 <= i <= len(hosts)] + selected = [hosts[i - 1] for i in indices if 1 <= i <= len(hosts)] 
-            if selected: + if selected: 
-                return selected + return selected 
-        except: + except: 
-            pass + pass 
- +   
-        safe_print("Sélection invalide."+ safe_print("Sélection invalide."
- +   
- +   
-def main(): + def main(): 
-    hosts = load_hosts(SWITCH_FILE) + hosts = load_hosts(SWITCH_FILE) 
-    if not hosts: + if not hosts: 
-        safe_print(f"Erreur : fichier {SWITCH_FILE} introuvable ou vide."+ safe_print(f"Erreur : fichier {SWITCH_FILE} introuvable ou vide."
-        return + return 
- +   
-    safe_print(f"{len(hosts)} switches chargés."+ safe_print(f"{len(hosts)} switches chargés."
- +   
-    username = input("Identifiant SSH : ").strip() + username = input("Identifiant SSH : ").strip() 
-    password = getpass("Mot de passe SSH : ") + password = getpass("Mot de passe SSH : ") 
- +   
-    current_selection = hosts  # par défaut : tous + current_selection = hosts  # par défaut : tous 
- +   
-    while True: + while True: 
-        safe_print("\n====== MENU PRINCIPAL ======"+ safe_print("\n====== MENU PRINCIPAL ======"
-        safe_print("Switches sélectionnés :") + safe_print("Switches sélectionnés :") 
-        for h in current_selection: + for h in current_selection: 
-            safe_print(f"  - {h}"+ safe_print(f"  - {h}"
- +   
-        safe_print("\nOptions :") + safe_print("\nOptions :") 
-        safe_print("  cmd   -> taper des commandes"+ safe_print("  cmd   -> taper des commandes"
-        safe_print("  sel   -> changer la sélection"+ safe_print("  sel   -> changer la sélection"
-        safe_print("  clear -> effacer l'écran"+ safe_print("  clear -> effacer l'écran"
-        safe_print("  exit  -> quitter"+ safe_print("  exit  -> quitter"
-        safe_print("============================"+ safe_print("============================"
- +   
-        choice = input("> ").strip().lower() + choice = input("> ").strip().lower() 
- +   
-        if choice == "exit": + if choice == "exit": 
-            return + return 
- +   
-        if choice == "clear": + if choice == "clear": 
-            os.system("cls" if os.name == "nt" else "clear"+ os.system("cls" if os.name == "nt" else "clear"
-            continue + continue 
- +   
-        if choice == "sel": + if choice == "sel": 
-            new_sel = choose_switches(hosts) + new_sel = choose_switches(hosts) 
-            if new_sel: + if new_sel: 
-                current_selection = new_sel + current_selection = new_sel 
-            continue + continue 
- +   
-        if choice == "cmd": + if choice == "cmd": 
-            safe_print("Entrez vos commandes (ligne vide pour lancer l'exécution)."+ safe_print("Entrez vos commandes (ligne vide pour lancer l'exécution)."
-            commands = [] + commands = [] 
- +   
-            while True: + while True: 
-                cmd = input("> ").strip() + cmd = input("> ").strip() 
-                if cmd == "": + if cmd == "": 
-                    if commands: + if commands: 
-                        break + break 
-                    else: + else: 
-                        continue + continue 
-                commands.append(cmd) + commands.append(cmd) 
- +   
-            safe_print("\n====== EXÉCUTION ======\n"+ safe_print("\n====== EXÉCUTION ======\n"
- +   
-            start_all = datetime.now() + start_all = datetime.now() 
- +   
-            results = [] + results = [] 
-            with ThreadPoolExecutor(max_workers=min(MAX_WORKERS, len(current_selection))) as pool: + with ThreadPoolExecutor(max_workers=min(MAX_WORKERS, len(current_selection))) as pool: 
-                future_map = { + future_map = { 
-                    pool.submit(run_on_switch, h, username, password, commands): h + pool.submit(run_on_switch, h, username, password, commands): h 
-                    for h in current_selection + for h in current_selection 
-                +
- +   
-                for f in as_completed(future_map): + for f in as_completed(future_map): 
-                    results.append(f.result()) + results.append(f.result()) 
- +   
-            # --- Résumé synthétique --- + # --- Résumé synthétique --- 
-            safe_print("\n======= RÉSUMÉ ======="+ safe_print("\n======= RÉSUMÉ ======="
-            for r in results: + for r in results: 
-                host = r["host"+ host = r["host"
-                status = "OK" if r["success"] else "ERREUR" + status = "OK" if r["success"] else "ERREUR" 
-                lines = len(r["lines"]) + lines = len(r["lines"]) 
-                dur = (r["end"] - r["start"]).total_seconds() + dur = (r["end"] - r["start"]).total_seconds() 
-                safe_print(f"- {host}: {status} | lignes: {lines} | durée: {dur:.1f}s"+ safe_print(f"- {host}: {status} | lignes: {lines} | durée: {dur:.1f}s"
-                if r["error"]: + if r["error"]: 
-                    safe_print(f"    -> {r['error']}"+ safe_print(f"    -> {r['error']}"
- +   
-            total = (datetime.now() - start_all).total_seconds() + total = (datetime.now() - start_all).total_seconds() 
-            safe_print(f"Durée totale : {total:.1f}s"+ safe_print(f"Durée totale : {total:.1f}s"
-            safe_print("=======================\n"+ safe_print("=======================\n"
 +   
 +   
 + if __name__ == "__main__": 
 + main()
  
-if __name__ == "__main__": 
-    main() 
  
  
scripts.1764854460.txt.gz · Dernière modification : 2025/12/04 14:21 de huracan

DokuWiki Appliance - Powered by TurnKey Linux