#!/usr/bin/env python3 """ SP NETWORKING ACADEMY BGP LAB - CONFIGURATION AND AUTOMATION Routers: R1 - AS65001 R2 - AS65002 R3 - AS65001 R4 - AS65002 BGP Sessions: R1-R2 : eBGP R1-R3 : iBGP R2-R4 : iBGP R3-R4 : eBGP Features: 1. Automatic SSH authentication. 2. Configure BGP on all four routers. 3. Advertise Loopback0 /32 prefixes. 4. Verify all BGP neighbors. 5. Retry remote route verification for up to 120 seconds. 6. Collect diagnostic output when routes are missing. 7. Generate one consolidated report. Startup configuration is NOT saved. """ from datetime import datetime from pathlib import Path import re import sys import time import traceback from netmiko import ConnectHandler from netmiko.exceptions import ( NetmikoAuthenticationException, NetmikoTimeoutException ) # ================================================== # 1. PROJECT CONFIGURATION # ================================================== SCRIPT_DIR = Path(__file__).resolve().parent PROJECT_DIR = SCRIPT_DIR.parent REPORT_DIR = PROJECT_DIR / "REPORTS" USERNAME = "admin" PASSWORD = "cisco123" MASK = "255.255.255.255" MAX_NEIGHBOR_WAIT = 120 NEIGHBOR_POLL_INTERVAL = 5 MAX_ROUTE_WAIT = 120 ROUTE_POLL_INTERVAL = 10 # ================================================== # 2. ROUTER AND BGP CONFIGURATION # ================================================== ROUTERS = { "R1": { "host": "10.0.31.1", "asn": 65001, "router_id": "1.1.1.1", "loopback": "172.16.1.1", "neighbors": { "11.1.1.2": 65002, "13.1.1.2": 65001 } }, "R2": { "host": "10.0.32.1", "asn": 65002, "router_id": "2.2.2.2", "loopback": "172.16.2.2", "neighbors": { "11.1.1.1": 65001, "12.1.1.2": 65002 } }, "R3": { "host": "10.0.33.1", "asn": 65001, "router_id": "3.3.3.3", "loopback": "172.16.3.3", "neighbors": { "13.1.1.1": 65001, "14.1.1.2": 65002 } }, "R4": { "host": "10.0.34.1", "asn": 65002, "router_id": "4.4.4.4", "loopback": "172.16.4.4", "neighbors": { "12.1.1.1": 65002, "14.1.1.1": 65001 } } } # ================================================== # 3. COMMON SSH CONNECTION # ================================================== def create_connection(host): device = { "device_type": "cisco_ios", "host": host, "username": USERNAME, "password": PASSWORD, "conn_timeout": 15, "auth_timeout": 20, "banner_timeout": 20, "fast_cli": False } return ConnectHandler(**device) # ================================================== # 4. GET EXPECTED REMOTE PREFIXES # ================================================== def get_remote_prefixes(router_name): return [ details["loopback"] for name, details in ROUTERS.items() if name != router_name ] # ================================================== # 5. CONFIGURE BGP ON EACH ROUTER # ================================================== def configure_bgp(router_name, details): host = details["host"] asn = details["asn"] router_id = details["router_id"] loopback = details["loopback"] log = [] log.append("\n" + "=" * 80) log.append(f"BGP CONFIGURATION - {router_name}") log.append(f"Management IP : {host}") log.append(f"Local AS : {asn}") log.append(f"Router ID : {router_id}") log.append(f"Loopback : {loopback}/32") log.append("=" * 80) connection = None success = False try: print(f"\n[INFO] Connecting to {router_name} ({host})") connection = create_connection(host) print(f"[PASS] SSH connected to {router_name}") log.append("\nSSH CONNECTION: PASS") # ------------------------------------------ # CHECK EXISTING BGP CONFIGURATION # ------------------------------------------ existing = connection.send_command( "show running-config | section ^router bgp" ) log.append("\nEXISTING BGP CONFIGURATION:") log.append( existing if existing.strip() else "No BGP configuration found" ) bgp_processes = re.findall( r"(?m)^router bgp\s+(\d+)", existing ) if bgp_processes: if len(bgp_processes) != 1 or int(bgp_processes[0]) != asn: raise RuntimeError( f"Unexpected existing BGP process: {bgp_processes}. " f"Expected AS {asn}. Configuration stopped." ) # ------------------------------------------ # BUILD BGP CONFIGURATION # ------------------------------------------ commands = [ f"router bgp {asn}", f"bgp router-id {router_id}", "bgp log-neighbor-changes" ] for neighbor, remote_as in details["neighbors"].items(): commands.append( f"neighbor {neighbor} remote-as {remote_as}" ) commands.append( f"network {loopback} mask {MASK}" ) log.append("\nCONFIGURATION COMMANDS:") for command in commands: log.append(command) # ------------------------------------------ # APPLY CONFIGURATION # ------------------------------------------ print(f"[INFO] {router_name}: Configuring BGP AS {asn}") output = connection.send_config_set( commands, cmd_verify=True ) log.append("\nCONFIGURATION OUTPUT:") log.append(output) # ------------------------------------------ # VERIFY RUNNING CONFIGURATION # ------------------------------------------ verify_config = connection.send_command( "show running-config | section ^router bgp" ) log.append("\nBGP CONFIGURATION AFTER DEPLOYMENT:") log.append(verify_config) expected_lines = [ f"router bgp {asn}", f"bgp router-id {router_id}", f"network {loopback} mask {MASK}" ] if all(item in verify_config for item in expected_lines): success = True print(f"[PASS] {router_name}: BGP configuration verified") log.append("\nCONFIGURATION VERIFICATION: PASS") else: print(f"[FAIL] {router_name}: Configuration verification failed") log.append("\nCONFIGURATION VERIFICATION: FAIL") except NetmikoAuthenticationException as exc: log.append(f"\nAUTHENTICATION ERROR: {exc}") print(f"[FAIL] {router_name}: Authentication failed") except NetmikoTimeoutException as exc: log.append(f"\nCONNECTION TIMEOUT: {exc}") print(f"[FAIL] {router_name}: Connection timeout") except Exception as exc: log.append(f"\nERROR: {type(exc).__name__}: {exc}") log.append(traceback.format_exc()) print(f"[FAIL] {router_name}: {exc}") finally: if connection: try: connection.disconnect() except Exception: pass log.append( f"\nCONFIGURATION RESULT: {'PASS' if success else 'FAIL'}" ) return success, "\n".join(log) # ================================================== # 6. VERIFY BGP NEIGHBORS WITH RETRIES # ================================================== def verify_bgp_neighbors(router_name, details): host = details["host"] neighbors = details["neighbors"] log = [] log.append("\n" + "=" * 80) log.append(f"BGP NEIGHBOR VERIFICATION - {router_name}") log.append("=" * 80) connection = None success = False try: connection = create_connection(host) print(f"\n[INFO] {router_name}: Checking BGP neighbors") start_time = time.time() attempt = 0 last_output = "" while time.time() - start_time < MAX_NEIGHBOR_WAIT: attempt += 1 last_output = connection.send_command( "show ip bgp summary" ) states = {} for neighbor in neighbors: neighbor_line = next( ( line.strip() for line in last_output.splitlines() if line.strip().startswith(neighbor) ), "" ) fields = neighbor_line.split() # In Cisco BGP summary, a numeric final field # indicates Established. It may be zero routes. established = ( bool(fields) and fields[0] == neighbor and fields[-1].isdigit() ) states[neighbor] = established if all(states.values()): success = True break print( f"[INFO] {router_name}: " f"Neighbor retry {attempt}" ) time.sleep(NEIGHBOR_POLL_INTERVAL) log.append(f"\nVerification attempts: {attempt}") log.append("\nCOMMAND: show ip bgp summary") log.append(last_output) log.append("\nNEIGHBOR STATUS:") for neighbor, remote_as in neighbors.items(): state = states.get(neighbor, False) status = ( "ESTABLISHED" if state else "NOT ESTABLISHED" ) log.append( f"{neighbor} | Remote AS {remote_as} | {status}" ) print( f"[{'PASS' if state else 'FAIL'}] " f"{router_name} -> {neighbor}: {status}" ) log.append( f"\nNEIGHBOR VERIFICATION: " f"{'PASS' if success else 'FAIL'}" ) except Exception as exc: success = False log.append(f"\nERROR: {type(exc).__name__}: {exc}") log.append(traceback.format_exc()) print(f"[FAIL] {router_name}: Neighbor verification error") finally: if connection: try: connection.disconnect() except Exception: pass return success, "\n".join(log) # ================================================== # 7. VERIFY BGP ROUTES WITH RETRIES # ================================================== def verify_bgp_routes(router_name, details): host = details["host"] prefixes = get_remote_prefixes(router_name) log = [] log.append("\n" + "=" * 80) log.append(f"BGP ROUTE VERIFICATION - {router_name}") log.append("=" * 80) connection = None success = False try: connection = create_connection(host) print( f"\n[INFO] {router_name}: " "Waiting for BGP route convergence" ) start_time = time.time() attempt = 0 received_prefixes = set() # ------------------------------------------ # ROUTE CONVERGENCE RETRY LOOP # ------------------------------------------ while time.time() - start_time < MAX_ROUTE_WAIT: attempt += 1 received_prefixes.clear() print( f"\n[INFO] {router_name}: " f"Route verification attempt {attempt}" ) for prefix in prefixes: output = connection.send_command( f"show ip bgp {prefix}" ) route_present = ( prefix in output and "not in table" not in output.lower() ) if route_present: received_prefixes.add(prefix) print( f"[PASS] {router_name}: " f"BGP route {prefix} received" ) else: print( f"[WAIT] {router_name}: " f"BGP route {prefix} not received yet" ) # All three remote prefixes received if len(received_prefixes) == len(prefixes): success = True print( f"\n[PASS] {router_name}: " "All remote BGP prefixes received" ) break elapsed = int(time.time() - start_time) remaining = MAX_ROUTE_WAIT - elapsed if remaining <= 0: break print( f"[INFO] {router_name}: " f"Waiting {min(ROUTE_POLL_INTERVAL, remaining)} " "seconds before next attempt" ) time.sleep( min(ROUTE_POLL_INTERVAL, remaining) ) # ------------------------------------------ # FINAL PREFIX VERIFICATION # ------------------------------------------ elapsed = int(time.time() - start_time) log.append(f"\nTotal attempts: {attempt}") log.append(f"Total wait time: {elapsed} seconds") log.append("\nFINAL REMOTE PREFIX STATUS:") final_missing = [] for prefix in prefixes: output = connection.send_command( f"show ip bgp {prefix}" ) route_present = ( prefix in output and "not in table" not in output.lower() ) log.append(f"\nCOMMAND: show ip bgp {prefix}") log.append(output) if route_present: log.append(f"ROUTE {prefix}: PASS") else: final_missing.append(prefix) log.append(f"ROUTE {prefix}: FAIL") success = len(final_missing) == 0 # ------------------------------------------ # DIAGNOSTICS IF ANY ROUTE IS MISSING # ------------------------------------------ if not success: print( f"\n[WARNING] {router_name}: " "Some routes remain missing after retries" ) diagnostic_commands = [ "show ip bgp summary", "show ip bgp", "show ip route" ] for command in diagnostic_commands: output = connection.send_command(command) log.append(f"\nDIAGNOSTIC COMMAND: {command}") log.append(output) # Check local Loopback0 route local_loopback = details["loopback"] command = f"show ip route {local_loopback}" output = connection.send_command(command) log.append(f"\nDIAGNOSTIC COMMAND: {command}") log.append(output) # Check advertisements to every neighbor for neighbor in details["neighbors"]: command = ( f"show ip bgp neighbors " f"{neighbor} advertised-routes" ) output = connection.send_command(command) log.append(f"\nDIAGNOSTIC COMMAND: {command}") log.append(output) log.append( f"\nROUTE VERIFICATION: " f"{'PASS' if success else 'FAIL'}" ) except Exception as exc: success = False log.append(f"\nERROR: {type(exc).__name__}: {exc}") log.append(traceback.format_exc()) print(f"[FAIL] {router_name}: Route verification error") finally: if connection: try: connection.disconnect() except Exception: pass return success, "\n".join(log) # ================================================== # 8. MAIN EXECUTION # ================================================== def main(): REPORT_DIR.mkdir(parents=True, exist_ok=True) timestamp = datetime.now().strftime("%Y%m%d_%H%M%S") report_file = ( REPORT_DIR / f"BGP-CONFIGURATION-REPORT-{timestamp}.txt" ) print("=" * 80) print("SP NETWORKING ACADEMY") print("BGP CONFIGURATION AUTOMATION") print("=" * 80) print(f"Execution started: {datetime.now()}") print("SSH authentication: Automatic") print("Routers: R1, R2, R3, R4") configuration_results = {} neighbor_results = {} route_results = {} all_logs = [] # ---------------------------------------------- # PHASE 1 - CONFIGURE ALL ROUTERS # ---------------------------------------------- print("\n" + "=" * 80) print("PHASE 1 - BGP CONFIGURATION") print("=" * 80) for router_name, details in ROUTERS.items(): success, router_log = configure_bgp( router_name, details ) configuration_results[router_name] = success all_logs.append(router_log) # ---------------------------------------------- # PHASE 2 - VERIFY BGP NEIGHBORS # ---------------------------------------------- print("\n" + "=" * 80) print("PHASE 2 - BGP NEIGHBOR VERIFICATION") print("=" * 80) for router_name, details in ROUTERS.items(): if configuration_results[router_name]: success, router_log = verify_bgp_neighbors( router_name, details ) else: success = False router_log = ( f"\n{router_name}: Neighbor verification skipped " "because configuration failed." ) neighbor_results[router_name] = success all_logs.append(router_log) # ---------------------------------------------- # PHASE 3 - VERIFY BGP ROUTES # ---------------------------------------------- print("\n" + "=" * 80) print("PHASE 3 - BGP ROUTE VERIFICATION") print("=" * 80) for router_name, details in ROUTERS.items(): if ( configuration_results[router_name] and neighbor_results[router_name] ): success, router_log = verify_bgp_routes( router_name, details ) else: success = False router_log = ( f"\n{router_name}: Route verification skipped " "because configuration or neighbor verification failed." ) route_results[router_name] = success all_logs.append(router_log) # ---------------------------------------------- # PHASE 4 - FINAL SUMMARY # ---------------------------------------------- print("\n" + "=" * 80) print("FINAL BGP AUTOMATION SUMMARY") print("=" * 80) passed_routers = 0 failed_routers = 0 summary_lines = [] for router_name, details in ROUTERS.items(): config_ok = configuration_results[router_name] neighbor_ok = neighbor_results[router_name] route_ok = route_results[router_name] router_pass = ( config_ok and neighbor_ok and route_ok ) if router_pass: passed_routers += 1 final_status = "PASS" else: failed_routers += 1 final_status = "FAIL" line = ( f"{router_name} ({details['host']}) | " f"CONFIG: {'PASS' if config_ok else 'FAIL'} | " f"NEIGHBORS: {'PASS' if neighbor_ok else 'FAIL'} | " f"ROUTES: {'PASS' if route_ok else 'FAIL'} | " f"FINAL: {final_status}" ) summary_lines.append(line) print(line) print(f"\nRouters passed: {passed_routers}/4") print(f"Routers failed: {failed_routers}/4") # ---------------------------------------------- # PHASE 5 - SINGLE CONSOLIDATED REPORT # ---------------------------------------------- with report_file.open("w", encoding="utf-8") as report: report.write( "SP NETWORKING ACADEMY\n" "BGP CONFIGURATION AND VERIFICATION REPORT\n" ) report.write(f"\nExecution time: {datetime.now()}\n") report.write("\n" + "=" * 80 + "\n") report.write("FINAL EXECUTION SUMMARY\n") report.write("=" * 80 + "\n") report.write("\n".join(summary_lines)) report.write(f"\n\nRouters passed: {passed_routers}/4") report.write(f"\nRouters failed: {failed_routers}/4") report.write("\n\nBGP DESIGN:") report.write("\nAS65001: R1 and R3") report.write("\nAS65002: R2 and R4") report.write("\neBGP: R1-R2 and R3-R4") report.write("\niBGP: R1-R3 and R2-R4") report.write("\n\nNEIGHBOR WAIT: 120 seconds maximum") report.write("\nROUTE WAIT: 120 seconds per router maximum") report.write("\n\nSTARTUP CONFIGURATION: NOT SAVED") report.write( "\n\n" + "=" * 80 + "\nDETAILED EXECUTION LOGS\n" + "=" * 80 ) report.write("\n".join(all_logs)) report.write( "\n\n" + "=" * 80 + "\nEND OF REPORT\n" + "=" * 80 + "\n" ) # ---------------------------------------------- # TERMINAL REPORT LOCATION # ---------------------------------------------- print(f"\nSingle consolidated report:") print(report_file) print("=" * 80) return 0 if failed_routers == 0 else 1 if __name__ == "__main__": sys.exit(main())