#!/usr/bin/env python3 """ SP Networking Academy - BGP Lab Collect complete running configurations from R1-R4. Read-only collection. No configuration commands are sent. SSH password is requested interactively and is not stored in this file. Run from /home/user/network-automation/BGP: python tests/get-running-config.py """ from datetime import datetime from getpass import getpass from pathlib import Path import sys import traceback from netmiko import ConnectHandler from netmiko.exceptions import ( NetmikoAuthenticationException, NetmikoTimeoutException, ) SCRIPT_DIR = Path(__file__).resolve().parent PROJECT_DIR = SCRIPT_DIR.parent REPORT_DIR = PROJECT_DIR / "REPORTS" ROUTERS = { "R1": "10.0.31.1", "R2": "10.0.32.1", "R3": "10.0.33.1", "R4": "10.0.34.1", } def collect_running_config(router_name, host, username, password, timestamp): lines = [ "=" * 80, f"SP NETWORKING ACADEMY - {router_name} RUNNING CONFIGURATION", f"Management IP : {host}", f"Collection time: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}", "=" * 80, "", ] connection = None success = False device = { "device_type": "cisco_ios", "host": host, "username": username, "password": password, "conn_timeout": 15, "auth_timeout": 20, "banner_timeout": 20, "fast_cli": False, } try: print(f"\n[INFO] Connecting to {router_name} ({host}) ...") connection = ConnectHandler(**device) print(f"[PASS] SSH connected to {router_name}") lines.append(f"Connection Status: PASS") lines.append(f"Device prompt: {connection.find_prompt()}") lines.append("") lines.append("-" * 80) lines.append("COMMAND: show running-config") lines.append("-" * 80) print(f"[INFO] {router_name}: collecting complete running configuration ...") output = connection.send_command( "show running-config", read_timeout=120, strip_prompt=False, strip_command=False, ) if output.strip(): lines.append(output) success = True print(f"[PASS] {router_name}: running configuration collected") else: lines.append("[WARNING] Command returned empty output.") print(f"[WARN] {router_name}: empty running-config output") except NetmikoAuthenticationException as exc: lines.extend(["Connection Status: FAIL - Authentication failed", str(exc)]) print(f"[FAIL] Authentication failed for {router_name}") except NetmikoTimeoutException as exc: lines.extend(["Connection Status: FAIL - Connection timeout", str(exc)]) print(f"[FAIL] Connection timeout for {router_name}") except Exception as exc: lines.extend([ f"Collection Status: FAIL - {type(exc).__name__}", str(exc), traceback.format_exc(), ]) print(f"[FAIL] {router_name}: {type(exc).__name__}: {exc}") finally: if connection: try: connection.disconnect() except Exception: pass lines.extend(["", f"Collection Result: {'PASS' if success else 'FAIL'}", ""]) report_text = "\n".join(lines) report_file = REPORT_DIR / f"{router_name}-RUNNING-CONFIG-{timestamp}.txt" report_file.write_text(report_text, encoding="utf-8") print(f"[INFO] Saved: {report_file}") return success, report_text, report_file def main(): REPORT_DIR.mkdir(parents=True, exist_ok=True) timestamp = datetime.now().strftime("%Y%m%d_%H%M%S") print("=" * 80) print("SP NETWORKING ACADEMY - FULL RUNNING CONFIGURATION BACKUP") print(f"Started: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}") print("=" * 80) username = input("SSH username [admin]: ").strip() or "admin" password = getpass("SSH password (input hidden): ") results = [] summary = [] passed = 0 failed = 0 for router_name, host in ROUTERS.items(): success, report_text, report_file = collect_running_config( router_name, host, username, password, timestamp ) results.append(report_text) if success: passed += 1 status = "PASS" else: failed += 1 status = "FAIL" summary.append(f"{router_name} ({host}): {status} | {report_file.name}") consolidated_file = REPORT_DIR / f"BGP-RUNNING-CONFIGS-{timestamp}.txt" with consolidated_file.open("w", encoding="utf-8") as report: report.write("SP NETWORKING ACADEMY - CONSOLIDATED RUNNING CONFIGURATIONS\n") report.write(f"Execution time: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\n") report.write("=" * 80 + "\n\n") report.write("COLLECTION SUMMARY\n") report.write("-" * 80 + "\n") report.write("\n".join(summary) + "\n") report.write(f"\nRouters collected: {passed}/4\n") report.write(f"Routers failed: {failed}/4\n\n") report.write("\n".join(results)) print("\n" + "=" * 80) print("RUNNING CONFIGURATION COLLECTION SUMMARY") print("=" * 80) for item in summary: print(item) print(f"\nRouters collected: {passed}/4") print(f"Routers failed: {failed}/4") print(f"Consolidated file: {consolidated_file}") print("=" * 80) return 0 if failed == 0 else 1 if __name__ == "__main__": sys.exit(main())