#!/usr/bin/env python3 """ SP NETWORKING ACADEMY BGP LAB - LOOPBACK CONFIGURATION AUTOMATION Enhancements: 1. Common SSH password configured in script. 2. No interactive password prompt. 3. One consolidated report for the entire execution. 4. Complete router-by-router command and verification logs. 5. Existing correct Loopback0 configuration is preserved. 6. Conflicting Loopback0 configuration is not overwritten. Startup configuration is NOT saved. """ from datetime import datetime from pathlib import Path import sys import traceback from netmiko import ConnectHandler from netmiko.exceptions import ( NetmikoAuthenticationException, NetmikoTimeoutException ) # -------------------------------------------------- # PROJECT CONFIGURATION # -------------------------------------------------- SCRIPT_DIR = Path(__file__).resolve().parent PROJECT_DIR = SCRIPT_DIR.parent REPORT_DIR = PROJECT_DIR / "REPORTS" ROUTERS = { "R1": {"host": "10.0.31.1", "loopback": "172.16.1.1"}, "R2": {"host": "10.0.32.1", "loopback": "172.16.2.2"}, "R3": {"host": "10.0.33.1", "loopback": "172.16.3.3"}, "R4": {"host": "10.0.34.1", "loopback": "172.16.4.4"} } USERNAME = "admin" PASSWORD = "cisco123" MASK = "255.255.255.255" # -------------------------------------------------- # ROUTER CONFIGURATION FUNCTION # -------------------------------------------------- def configure_router(router_name, details, timestamp): host = details["host"] loopback_ip = details["loopback"] lines = [ "\n" + "=" * 80, f"ROUTER: {router_name}", f"MANAGEMENT IP: {host}", f"EXPECTED LOOPBACK: {loopback_ip}/32", f"START TIME: {datetime.now()}", "=" * 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("\nSSH CONNECTION: PASS") lines.append(f"Device prompt: {connection.find_prompt()}") # ------------------------------------------ # STEP 1 - CHECK EXISTING CONFIGURATION # ------------------------------------------ print(f"[INFO] {router_name}: Checking Loopback0") existing = connection.send_command( "show running-config | section ^interface Loopback0" ) lines.append("\nCOMMAND: show running-config | section ^interface Loopback0") lines.append(existing if existing.strip() else "Loopback0 not configured") expected_line = f"ip address {loopback_ip} {MASK}" if existing.strip(): if expected_line in existing: print(f"[PASS] {router_name}: Correct Loopback0 already exists") lines.append("\nRESULT: Existing Loopback0 matches expected configuration") else: raise RuntimeError( "Loopback0 exists with a different configuration. " "No changes made." ) else: # -------------------------------------- # STEP 2 - CONFIGURE LOOPBACK0 # -------------------------------------- print(f"[INFO] {router_name}: Configuring Loopback0") commands = [ "interface Loopback0", f"ip address {loopback_ip} {MASK}" ] output = connection.send_config_set( commands, cmd_verify=True ) lines.append("\nCONFIGURATION COMMANDS:") lines.extend(commands) lines.append("\nCONFIGURATION OUTPUT:") lines.append(output) # ------------------------------------------ # STEP 3 - VERIFY INTERFACE # ------------------------------------------ print(f"[INFO] {router_name}: Verifying Loopback0") interface_output = connection.send_command( "show ip interface brief | include Loopback0" ) lines.append("\nCOMMAND: show ip interface brief | include Loopback0") lines.append(interface_output or "Loopback0 not found") # ------------------------------------------ # STEP 4 - VERIFY ROUTING TABLE # ------------------------------------------ route_output = connection.send_command( f"show ip route {loopback_ip}" ) lines.append(f"\nCOMMAND: show ip route {loopback_ip}") lines.append(route_output or "Route not found") # ------------------------------------------ # STEP 5 - FINAL VALIDATION # ------------------------------------------ if ( loopback_ip in interface_output and "up" in interface_output.lower() and loopback_ip in route_output and "connected" in route_output.lower() ): success = True print(f"[PASS] {router_name}: Loopback0 verified") lines.append("\nVERIFICATION: PASS") else: print(f"[FAIL] {router_name}: Loopback verification failed") lines.append("\nVERIFICATION: FAIL") except NetmikoAuthenticationException as exc: lines.append(f"\nAUTHENTICATION ERROR: {exc}") print(f"[FAIL] Authentication failed: {router_name}") except NetmikoTimeoutException as exc: lines.append(f"\nCONNECTION TIMEOUT: {exc}") print(f"[FAIL] Connection timeout: {router_name}") except Exception as exc: lines.append(f"\nERROR: {type(exc).__name__}: {exc}") lines.append(traceback.format_exc()) print(f"[FAIL] {router_name}: {exc}") finally: if connection: try: connection.disconnect() except Exception: pass lines.append(f"\nFINAL RESULT: {'PASS' if success else 'FAIL'}") lines.append(f"END TIME: {datetime.now()}") # Return complete router log to main function. return success, "\n".join(lines) # -------------------------------------------------- # MAIN EXECUTION # -------------------------------------------------- def main(): REPORT_DIR.mkdir(parents=True, exist_ok=True) timestamp = datetime.now().strftime("%Y%m%d_%H%M%S") consolidated_file = ( REPORT_DIR / f"BGP-LOOPBACK-CONFIG-{timestamp}.txt" ) print("=" * 80) print("SP NETWORKING ACADEMY - LOOPBACK CONFIGURATION AUTOMATION") print("=" * 80) print(f"Execution started: {datetime.now()}") print("Connecting to all four routers...") print("Password authentication: Automatic") passed = 0 failed = 0 summary = [] all_logs = [] # ---------------------------------------------- # PROCESS ALL FOUR ROUTERS # ---------------------------------------------- for router_name, details in ROUTERS.items(): success, router_log = configure_router( router_name, details, timestamp ) all_logs.append(router_log) if success: passed += 1 status = "PASS" else: failed += 1 status = "FAIL" summary.append( f"{router_name} ({details['host']}): {status}" ) # ---------------------------------------------- # GENERATE SINGLE CONSOLIDATED REPORT # ---------------------------------------------- with consolidated_file.open("w", encoding="utf-8") as report: report.write( "SP NETWORKING ACADEMY\n" "BGP LAB - LOOPBACK CONFIGURATION AUTOMATION\n" ) report.write(f"\nExecution time: {datetime.now()}\n") report.write("\n" + "=" * 80 + "\n") report.write("EXECUTION SUMMARY\n") report.write("=" * 80 + "\n") report.write("\n".join(summary)) report.write(f"\n\nRouters passed: {passed}/4") report.write(f"\nRouters failed: {failed}/4") report.write("\n\nSTARTUP CONFIGURATION: NOT SAVED") report.write("\n\n" + "=" * 80) report.write("\nDETAILED ROUTER EXECUTION LOGS\n") report.write("\n" + "=" * 80) report.write("\n".join(all_logs)) report.write("\n\n" + "=" * 80) report.write("\nEND OF REPORT") report.write("\n" + "=" * 80 + "\n") # ---------------------------------------------- # TERMINAL SUMMARY # ---------------------------------------------- print("\n" + "=" * 80) print("LOOPBACK CONFIGURATION EXECUTION SUMMARY") print("=" * 80) for item in summary: print(item) print(f"\nRouters passed: {passed}/4") print(f"Routers failed: {failed}/4") print(f"\nSingle consolidated report:") print(consolidated_file) print("=" * 80) return 0 if failed == 0 else 1 if __name__ == "__main__": sys.exit(main())