#!/usr/bin/env python3 """ SP NETWORKING ACADEMY BGP LAB - OSPF REMOVAL AUTOMATION Purpose: 1. Connect to R1, R2, R3 and R4 using Netmiko. 2. Collect existing OSPF configuration. 3. Remove OSPF process 1. 4. Verify OSPF configuration removal. 5. Generate individual and consolidated reports. WARNING: This script changes router configuration. It does NOT save changes to startup-config. """ 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 CONFIGURATION # -------------------------------------------------- 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" } CONFIG_COMMANDS = [ "no router ospf 1" ] VERIFY_COMMAND = "show running-config | section router ospf" # -------------------------------------------------- # ROUTER CONFIGURATION FUNCTION # -------------------------------------------------- def configure_router(router_name, host, username, password, timestamp): lines = [ "=" * 80, f"SP NETWORKING ACADEMY - OSPF REMOVAL: {router_name}", f"Management IP: {host}", f"Execution 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("SSH Connection: PASS") # ------------------------------------------ # STEP 1 - CHECK EXISTING OSPF CONFIGURATION # ------------------------------------------ print(f"[INFO] {router_name}: Checking existing OSPF configuration") before = connection.send_command( "show running-config | section router ospf" ) lines.append("\nBEFORE CONFIGURATION") lines.append(before if before.strip() else "No OSPF configuration found") if not before.strip(): lines.append("\nRESULT: OSPF was not configured") print(f"[INFO] {router_name}: OSPF already absent") success = True else: # -------------------------------------- # STEP 2 - REMOVE OSPF PROCESS # -------------------------------------- print(f"[INFO] {router_name}: Removing OSPF process 1") output = connection.send_config_set( CONFIG_COMMANDS, cmd_verify=True ) lines.append("\nCONFIGURATION COMMAND") lines.append("no router ospf 1") lines.append(output) # -------------------------------------- # STEP 3 - VERIFY REMOVAL # -------------------------------------- print(f"[INFO] {router_name}: Verifying OSPF removal") after = connection.send_command( VERIFY_COMMAND ) lines.append("\nAFTER CONFIGURATION") lines.append( after if after.strip() else "OSPF configuration successfully removed" ) if not after.strip(): success = True lines.append("\nVERIFICATION: PASS") print(f"[PASS] {router_name}: OSPF removed successfully") else: lines.append("\nVERIFICATION: FAIL") print(f"[FAIL] {router_name}: OSPF configuration still present") lines.append( f"\nFINAL RESULT: {'PASS' if success else 'FAIL'}" ) except NetmikoAuthenticationException as exc: lines.append(f"AUTHENTICATION ERROR: {exc}") print(f"[FAIL] Authentication failed: {router_name}") except NetmikoTimeoutException as exc: lines.append(f"CONNECTION TIMEOUT: {exc}") print(f"[FAIL] Connection timeout: {router_name}") except Exception as exc: lines.append(f"ERROR: {type(exc).__name__}: {exc}") lines.append(traceback.format_exc()) print(f"[FAIL] {router_name}: {exc}") finally: if connection: try: connection.disconnect() except Exception: pass report_file = ( REPORT_DIR / f"{router_name}-OSPF-REMOVAL-{timestamp}.txt" ) report_file.write_text( "\n".join(lines), encoding="utf-8" ) print(f"[INFO] Report saved: {report_file}") return success, report_file # -------------------------------------------------- # MAIN EXECUTION # -------------------------------------------------- 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 - OSPF REMOVAL AUTOMATION") print("=" * 80) username = input("SSH username [admin]: ").strip() or "admin" password = getpass("SSH password (hidden): ") passed = 0 failed = 0 summary = [] # ---------------------------------------------- # PROCESS ALL FOUR ROUTERS # ---------------------------------------------- for router_name, host in ROUTERS.items(): success, report_file = configure_router( router_name, host, username, password, timestamp ) if success: passed += 1 status = "PASS" else: failed += 1 status = "FAIL" summary.append( f"{router_name} ({host}): {status}" ) # ---------------------------------------------- # CONSOLIDATED REPORT # ---------------------------------------------- consolidated_file = ( REPORT_DIR / f"BGP-OSPF-REMOVAL-SUMMARY-{timestamp}.txt" ) with consolidated_file.open("w", encoding="utf-8") as report: report.write( "SP NETWORKING ACADEMY - OSPF REMOVAL SUMMARY\n" ) report.write(f"Execution Time: {datetime.now()}\n") report.write("=" * 80 + "\n") report.write("\nROUTER RESULTS\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\nNOTE: Configuration not saved to startup-config.") # ---------------------------------------------- # FINAL TERMINAL SUMMARY # ---------------------------------------------- print("\n" + "=" * 80) print("OSPF REMOVAL EXECUTION SUMMARY") print("=" * 80) for item in summary: print(item) print(f"\nRouters Passed: {passed}/4") print(f"Routers Failed: {failed}/4") print(f"\nConsolidated Report: {consolidated_file}") print("=" * 80) return 0 if failed == 0 else 1 if __name__ == "__main__": sys.exit(main())