#!/usr/bin/env python3 """ SP NETWORKING ACADEMY BGP-008 - BGP FAILURE AND RECOVERY AUTOMATION Scenario: 1. Capture initial R1-R2 BGP state. 2. Shut R1 FastEthernet0/0. 3. Verify neighbor failure detection. 4. Verify alternate route availability. 5. Restore R1 FastEthernet0/0. 6. Verify BGP neighbor recovery. 7. Verify route recovery. IMPORTANT: Only R1 Fa0/0 is modified. Automatic interface restoration is attempted in finally. """ import re import sys import time from pathlib import Path from datetime import datetime from netmiko import ConnectHandler # -------------------------------------------------- # CONFIGURATION # -------------------------------------------------- BASE_DIR = Path(__file__).resolve().parent.parent REPORT_DIR = BASE_DIR / "REPORTS" REPORT_DIR.mkdir(parents=True, exist_ok=True) ROUTER = "R1" HOST = "10.0.31.1" USERNAME = "admin" PASSWORD = "cisco123" INTERFACE = "FastEthernet0/0" NEIGHBOR_IP = "11.1.1.2" TEST_PREFIX = "172.16.2.2" POLL_INTERVAL = 5 MAX_WAIT = 90 TIMESTAMP = datetime.now().strftime("%Y%m%d_%H%M%S") REPORT_FILE = REPORT_DIR / f"BGP-008-FAILURE-RECOVERY-{TIMESTAMP}.txt" results = [] log_lines = [] passed = 0 failed = 0 restoration_ok = False # -------------------------------------------------- # LOGGING # -------------------------------------------------- def log(message): print(message) log_lines.append(message) def check_result(description, success, detail=""): global passed, failed status = "PASS" if success else "FAIL" if success: passed += 1 else: failed += 1 message = f"[{status}] {description}" if detail: message += f" | {detail}" log(message) results.append((description, status, detail)) return success # -------------------------------------------------- # DEVICE COMMANDS # -------------------------------------------------- def get_neighbor_state(connection): output = connection.send_command( "show ip bgp summary", read_timeout=30 ) for line in output.splitlines(): if line.strip().startswith(NEIGHBOR_IP): fields = line.split() if fields: last_field = fields[-1] # Numeric value means Established and # represents received prefix count. if last_field.isdigit(): return "ESTABLISHED" return last_field.upper() return "NOT_FOUND" def get_route_output(connection): return connection.send_command( f"show ip route {TEST_PREFIX}", read_timeout=30 ) def wait_for_neighbor(connection, expected, description): attempts = max(1, MAX_WAIT // POLL_INTERVAL) for attempt in range(1, attempts + 1): state = get_neighbor_state(connection) log( f"[INFO] {description} " f"| Attempt {attempt}/{attempts} " f"| State: {state}" ) if expected == "DOWN": if state != "ESTABLISHED": return True elif state == "ESTABLISHED": return True time.sleep(POLL_INTERVAL) return False def wait_for_alternate_route(connection): attempts = max(1, MAX_WAIT // POLL_INTERVAL) for attempt in range(1, attempts + 1): output = get_route_output(connection) log( f"[INFO] Alternate route verification " f"| Attempt {attempt}/{attempts}" ) route_exists = ( TEST_PREFIX in output or f"{TEST_PREFIX}/32" in output ) # Ensure the route is not still using the # failed direct R1-R2 next-hop. primary_next_hop = re.search( r"\bvia\s+11\.1\.1\.2\b", output ) if route_exists and not primary_next_hop: log(output) return True time.sleep(POLL_INTERVAL) log(output) return False # -------------------------------------------------- # MAIN EXECUTION # -------------------------------------------------- def main(): global restoration_ok connection = None shutdown_attempted = False log("=" * 78) log("SP NETWORKING ACADEMY - BGP-008 FAILURE AND RECOVERY") log("=" * 78) log(f"Execution started: {datetime.now()}") log(f"Router: {ROUTER} ({HOST})") log(f"Interface under test: {INTERFACE}") log(f"BGP neighbor: {NEIGHBOR_IP}") log(f"Test prefix: {TEST_PREFIX}") try: # ------------------------------------------ # CONNECT # ------------------------------------------ log(f"\n[INFO] Connecting to {ROUTER}") device = { "device_type": "cisco_ios", "host": HOST, "username": USERNAME, "password": PASSWORD, "conn_timeout": 15, "auth_timeout": 20, "banner_timeout": 20, "fast_cli": False, } connection = ConnectHandler(**device) check_result( "SSH connection", True, f"{ROUTER} connected" ) # ------------------------------------------ # PHASE 1 - INITIAL BASELINE # ------------------------------------------ log("\n" + "=" * 78) log("PHASE 1 - INITIAL BGP BASELINE") log("=" * 78) initial_state = get_neighbor_state(connection) check_result( "Initial BGP neighbor state", initial_state == "ESTABLISHED", initial_state ) initial_route = get_route_output(connection) check_result( "Initial test prefix availability", TEST_PREFIX in initial_route, TEST_PREFIX ) # Do not proceed if baseline is unhealthy. if initial_state != "ESTABLISHED": log("[FAIL] Initial neighbor is not Established.") return 1 if TEST_PREFIX not in initial_route: log("[FAIL] Initial test route is missing.") return 1 # ------------------------------------------ # PHASE 2 - CONTROLLED LINK FAILURE # ------------------------------------------ log("\n" + "=" * 78) log("PHASE 2 - SHUTDOWN PRIMARY LINK") log("=" * 78) log(f"[INFO] Shutting down {INTERFACE}") shutdown_attempted = True connection.send_config_set([ f"interface {INTERFACE}", "shutdown" ]) check_result( "Primary interface shutdown command", True, INTERFACE ) # ------------------------------------------ # PHASE 3 - NEIGHBOR FAILURE DETECTION # ------------------------------------------ log("\n" + "=" * 78) log("PHASE 3 - BGP FAILURE DETECTION") log("=" * 78) neighbor_down = wait_for_neighbor( connection, "DOWN", "BGP neighbor failure detection" ) check_result( "R1-R2 BGP neighbor transitioned down", neighbor_down, NEIGHBOR_IP ) # ------------------------------------------ # PHASE 4 - ALTERNATE ROUTE # ------------------------------------------ log("\n" + "=" * 78) log("PHASE 4 - ALTERNATE PATH VERIFICATION") log("=" * 78) alternate_route = wait_for_alternate_route( connection ) check_result( "Alternate route remains available", alternate_route, TEST_PREFIX ) except Exception as exc: check_result( "Test execution", False, str(exc) ) finally: # ------------------------------------------ # PHASE 5 - AUTOMATIC RESTORATION # ------------------------------------------ log("\n" + "=" * 78) log("PHASE 5 - PRIMARY LINK RESTORATION") log("=" * 78) if connection and shutdown_attempted: try: log( f"[INFO] Restoring {INTERFACE}" ) connection.send_config_set([ f"interface {INTERFACE}", "no shutdown" ]) time.sleep(3) interface_output = connection.send_command( f"show ip interface brief", read_timeout=30 ) interface_up = False for line in interface_output.splitlines(): if INTERFACE in line: fields = line.split() if len(fields) >= 6: interface_up = ( fields[-2].lower() == "up" and fields[-1].lower() == "up" ) restoration_ok = check_result( "Primary interface restored", interface_up, INTERFACE ) except Exception as exc: restoration_ok = False check_result( "Primary interface restoration", False, str(exc) ) elif not shutdown_attempted: restoration_ok = True log("[INFO] No shutdown was attempted; no restoration needed.") # ------------------------------------------ # PHASE 6 - BGP RECOVERY # ------------------------------------------ if connection and shutdown_attempted and restoration_ok: log("\n" + "=" * 78) log("PHASE 6 - BGP NEIGHBOR RECOVERY") log("=" * 78) try: neighbor_recovered = wait_for_neighbor( connection, "ESTABLISHED", "BGP neighbor recovery" ) check_result( "R1-R2 BGP neighbor recovered", neighbor_recovered, NEIGHBOR_IP ) time.sleep(3) recovered_route = get_route_output(connection) check_result( "Test prefix available after recovery", TEST_PREFIX in recovered_route, TEST_PREFIX ) except Exception as exc: check_result( "BGP recovery verification", False, str(exc) ) elif shutdown_attempted and not restoration_ok: check_result( "BGP recovery verification", False, "Skipped because interface restoration failed" ) if connection: try: connection.disconnect() log("[INFO] Disconnected from R1") except Exception: pass # ---------------------------------------------- # FINAL SUMMARY # ---------------------------------------------- log("\n" + "=" * 78) log("BGP-008 EXECUTION SUMMARY") log("=" * 78) for description, status, detail in results: log(f"{status}: {description} {detail}") log(f"\nChecks passed: {passed}") log(f"Checks failed: {failed}") final_status = ( "PASS" if failed == 0 and restoration_ok else "FAIL" ) log(f"FINAL STATUS: {final_status}") log(f"\nSingle consolidated report:") log(str(REPORT_FILE)) log("=" * 78) REPORT_FILE.write_text( "\n".join(log_lines) + "\n", encoding="utf-8" ) print(f"\n[INFO] Report saved: {REPORT_FILE}") return 0 if final_status == "PASS" else 1 if __name__ == "__main__": sys.exit(main())