#!/usr/bin/env python3 """ SP Networking Academy - BGP Lab Basic router inventory and baseline collection. Connects to R1-R4 using SSH/Netmiko and collects read-only interface, routing, OSPF, protocol and running-configuration details. Run from the BGP project directory: python tests/get-router-details.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, ) # Project paths SCRIPT_DIR = Path(__file__).resolve().parent PROJECT_DIR = SCRIPT_DIR.parent REPORT_DIR = PROJECT_DIR / "REPORTS" # OOB management addresses confirmed from Ubuntu: # R1 10.0.31.1, R2 10.0.32.1, R3 10.0.33.1, R4 10.0.34.1 ROUTERS = { "R1": "10.0.31.1", "R2": "10.0.32.1", "R3": "10.0.33.1", "R4": "10.0.34.1", } COMMANDS = [ "show ip interface brief", "show ip route", "show ip ospf neighbor", "show ip protocols", "show running-config", ] def collect_router(router_name, host, username, password, timestamp): """Connect to one router, collect commands, and save its report.""" lines = [] lines.append("=" * 78) lines.append(f"SP NETWORKING ACADEMY - ROUTER BASELINE: {router_name}") lines.append(f"Management IP : {host}") lines.append(f"Collection time: {timestamp}") lines.append("=" * 78) device = { "device_type": "cisco_ios", "host": host, "username": username, "password": password, "conn_timeout": 15, "auth_timeout": 20, "banner_timeout": 20, "fast_cli": False, } connection = None success = False try: print(f"\n[INFO] Connecting to {router_name} ({host}) ...") connection = ConnectHandler(**device) print(f"[PASS] SSH connected to {router_name}") lines.append("\nConnection Status: PASS") lines.append(f"Device prompt: {connection.find_prompt()}") for command in COMMANDS: print(f"[INFO] {router_name}: running '{command}'") lines.append("\n" + "-" * 78) lines.append(f"COMMAND: {command}") lines.append("-" * 78) try: output = connection.send_command( command, read_timeout=90 if command == "show running-config" else 30, strip_prompt=False, strip_command=False, ) lines.append(output if output.strip() else "[No output returned]") print(f"[PASS] {router_name}: {command}") except Exception as exc: error_text = f"[COMMAND ERROR] {type(exc).__name__}: {exc}" lines.append(error_text) print(f"[WARN] {router_name}: {command} - {exc}") success = True except NetmikoAuthenticationException as exc: lines.append("\nConnection Status: FAIL - Authentication failed") lines.append(str(exc)) print(f"[FAIL] Authentication failed for {router_name}") except NetmikoTimeoutException as exc: lines.append("\nConnection Status: FAIL - Connection timeout") lines.append(str(exc)) print(f"[FAIL] Connection timeout for {router_name}") except Exception as exc: lines.append(f"\nConnection Status: FAIL - {type(exc).__name__}") lines.append(str(exc)) lines.append(traceback.format_exc()) print(f"[FAIL] {router_name}: {type(exc).__name__}: {exc}") finally: if connection: try: connection.disconnect() except Exception: pass if success: lines.append("\nCollection Result: COMPLETED") else: lines.append("\nCollection Result: FAILED") report_text = "\n".join(lines) + "\n" report_file = REPORT_DIR / f"{router_name}-DETAILS-{timestamp}.txt" report_file.write_text(report_text, encoding="utf-8") print(f"[INFO] Report 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("=" * 78) print("SP NETWORKING ACADEMY - BGP ROUTER DETAILS COLLECTION") print(f"Started: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}") print("=" * 78) username = input("SSH username [admin]: ").strip() or "admin" password = getpass("SSH password (input hidden): ") all_results = [] summary = [] passed = 0 failed = 0 for router_name, host in ROUTERS.items(): success, report_text, report_file = collect_router( router_name, host, username, password, timestamp ) all_results.append(report_text) if success: passed += 1 status = "PASS" else: failed += 1 status = "FAIL" summary.append( f"{router_name} ({host}): {status} | Report: {report_file.name}" ) consolidated_file = REPORT_DIR / f"BGP-ROUTER-DETAILS-{timestamp}.txt" with consolidated_file.open("w", encoding="utf-8") as report: report.write("SP NETWORKING ACADEMY - CONSOLIDATED ROUTER BASELINE\n") report.write(f"Execution time: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\n") report.write("=" * 78 + "\n\n") report.write("EXECUTION SUMMARY\n") report.write("-" * 78 + "\n") report.write("\n".join(summary) + "\n") report.write(f"\nRouters passed: {passed}/4\n") report.write(f"Routers failed: {failed}/4\n") report.write("\n\n") report.write("\n".join(all_results)) print("\n" + "=" * 78) print("COLLECTION SUMMARY") print("=" * 78) for item in summary: print(item) print(f"\nRouters passed: {passed}/4") print(f"Routers failed: {failed}/4") print(f"Consolidated report: {consolidated_file}") print("=" * 78) # Non-zero exit code if any router connection failed. return 0 if failed == 0 else 1 if __name__ == "__main__": sys.exit(main())