#!/usr/bin/env python3 """ SP NETWORKING ACADEMY BGP-004 - ROUTE ADVERTISEMENT VERIFICATION Checks: 1. Local loopback prefix exists in BGP table. 2. All three remote loopback prefixes exist in BGP table. 3. Remote routes have a valid best path. 4. Remote routes are installed in the IP routing table. 5. Detect missing and unexpected BGP prefixes. Read-only test. Single consolidated report. """ from datetime import datetime from pathlib import Path import ipaddress 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" MAX_WAIT_SECONDS = 60 POLL_INTERVAL_SECONDS = 5 # ================================================== # 2. EXPECTED ROUTER AND PREFIX INFORMATION # ================================================== ROUTERS = { "R1": { "host": "10.0.31.1", "asn": 65001, "local_prefix": "172.16.1.1", "remote_prefixes": [ "172.16.2.2", "172.16.3.3", "172.16.4.4" ] }, "R2": { "host": "10.0.32.1", "asn": 65002, "local_prefix": "172.16.2.2", "remote_prefixes": [ "172.16.1.1", "172.16.3.3", "172.16.4.4" ] }, "R3": { "host": "10.0.33.1", "asn": 65001, "local_prefix": "172.16.3.3", "remote_prefixes": [ "172.16.1.1", "172.16.2.2", "172.16.4.4" ] }, "R4": { "host": "10.0.34.1", "asn": 65002, "local_prefix": "172.16.4.4", "remote_prefixes": [ "172.16.1.1", "172.16.2.2", "172.16.3.3" ] } } # ================================================== # 3. 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. BGP PREFIX VERIFICATION # ================================================== def check_bgp_prefix(connection, prefix): output = connection.send_command( f"show ip bgp {prefix}", read_timeout=30 ) lower_output = output.lower() missing_messages = [ "network not in table", "not in table", "% network not in table" ] if any(message in lower_output for message in missing_messages): return { "present": False, "best_path": False, "output": output } # Verify that the requested prefix appears in # the BGP routing table entry. prefix_pattern = ( r"BGP routing table entry for\s+" + re.escape(prefix) + r"/32" ) present = bool( re.search(prefix_pattern, output, re.IGNORECASE) ) # Verify valid and best path indication. best_path = bool( re.search( r"valid.*best|best.*valid", output, re.IGNORECASE ) ) return { "present": present, "best_path": best_path, "output": output } # ================================================== # 5. IP ROUTING TABLE VERIFICATION # ================================================== def check_ip_route(connection, prefix): output = connection.send_command( f"show ip route {prefix}", read_timeout=30 ) lower_output = output.lower() route_present = ( "routing entry for" in lower_output and "bgp" in lower_output ) return { "installed": route_present, "output": output } # ================================================== # 6. ROUTER TEST EXECUTION # ================================================== def test_router(router_name, details): host = details["host"] local_prefix = details["local_prefix"] remote_prefixes = details["remote_prefixes"] connection = None log = [] infrastructure_error = False local_result = False remote_results = {} unexpected_prefixes = [] start_time = time.time() attempt = 0 def record(message): log.append(message) record("\n" + "=" * 80) record("BGP-004 - ROUTE ADVERTISEMENT VERIFICATION") record(f"Router: {router_name}") record(f"Management IP: {host}") record("=" * 80) try: print(f"\n[INFO] Connecting to {router_name} ({host})") connection = create_connection(host) print(f"[PASS] SSH connected to {router_name}") record("INFRASTRUCTURE CONNECTION: PASS") # ------------------------------------------ # PHASE 1 - LOCAL PREFIX VERIFICATION # ------------------------------------------ print( f"\n[INFO] {router_name}: " "Checking local BGP prefix" ) local_check = check_bgp_prefix( connection, local_prefix ) local_result = ( local_check["present"] and local_check["best_path"] ) record("\nPHASE 1 - LOCAL PREFIX VERIFICATION") record(f"Prefix: {local_prefix}/32") record(local_check["output"]) if local_result: print( f"[PASS] {router_name}: " f"Local prefix {local_prefix}/32 " "present with valid best path" ) record("LOCAL PREFIX RESULT: PASS") else: print( f"[FAIL] {router_name}: " f"Local prefix {local_prefix}/32 " "missing or no valid best path" ) record("LOCAL PREFIX RESULT: FAIL") # ------------------------------------------ # PHASE 2 - REMOTE ROUTE CONVERGENCE # ------------------------------------------ print( f"\n[INFO] {router_name}: " "Waiting for remote BGP route convergence" ) while time.time() - start_time < MAX_WAIT_SECONDS: attempt += 1 print( f"\n[INFO] {router_name}: " f"Route verification attempt {attempt}" ) all_received = True for prefix in remote_prefixes: result = check_bgp_prefix( connection, prefix ) remote_results[prefix] = result if not ( result["present"] and result["best_path"] ): all_received = False print( f"[WAIT] {router_name}: " f"BGP route {prefix}/32 " "missing or no valid best path" ) else: print( f"[PASS] {router_name}: " f"BGP route {prefix}/32 received" ) if all_received: break remaining = ( MAX_WAIT_SECONDS - int(time.time() - start_time) ) if remaining <= 0: break wait_time = min( POLL_INTERVAL_SECONDS, remaining ) print( f"[INFO] {router_name}: " f"Retrying in {wait_time} seconds" ) time.sleep(wait_time) elapsed = int(time.time() - start_time) record("\nPHASE 2 - REMOTE BGP PREFIX VERIFICATION") record(f"Verification attempts: {attempt}") record(f"Elapsed time: {elapsed} seconds") # ------------------------------------------ # PHASE 3 - ROUTING TABLE VERIFICATION # ------------------------------------------ print( f"\n[INFO] {router_name}: " "Checking remote routes in IP routing table" ) route_results = {} for prefix in remote_prefixes: route_result = check_ip_route( connection, prefix ) route_results[prefix] = route_result record(f"\nCOMMAND: show ip route {prefix}") record(route_result["output"]) if route_result["installed"]: print( f"[PASS] {router_name}: " f"Route {prefix}/32 installed " "in IP routing table" ) else: print( f"[FAIL] {router_name}: " f"Route {prefix}/32 " "not installed through BGP" ) # ------------------------------------------ # PHASE 4 - UNEXPECTED PREFIX CHECK # ------------------------------------------ print( f"\n[INFO] {router_name}: " "Checking for unexpected BGP prefixes" ) bgp_table = connection.send_command( "show ip bgp", read_timeout=30 ) record("\nCOMMAND: show ip bgp") record(bgp_table) actual_prefixes = set() for line in bgp_table.splitlines(): match = re.match( r"^\s*[\*>sdhri]+?\s*" r"(\d+\.\d+\.\d+\.\d+/\d+)", line ) if match: actual_prefixes.add(match.group(1)) expected_prefixes = { f"{local_prefix}/32" } | { f"{prefix}/32" for prefix in remote_prefixes } unexpected_prefixes = sorted( actual_prefixes - expected_prefixes ) if unexpected_prefixes: for prefix in unexpected_prefixes: print( f"[FAIL] {router_name}: " f"Unexpected BGP prefix {prefix}" ) else: print( f"[PASS] {router_name}: " "No unexpected BGP prefixes" ) record("\nEXPECTED PREFIXES:") record(str(sorted(expected_prefixes))) record("\nACTUAL PREFIXES:") record(str(sorted(actual_prefixes))) record("\nUNEXPECTED PREFIXES:") record(str(unexpected_prefixes)) # ------------------------------------------ # FINAL ROUTER STATUS # ------------------------------------------ remote_passed = all( result["present"] and result["best_path"] for result in remote_results.values() ) route_passed = all( result["installed"] for result in route_results.values() ) router_pass = ( local_result and remote_passed and route_passed and not unexpected_prefixes ) record("\n" + "-" * 80) record(f"Local prefix: {'PASS' if local_result else 'FAIL'}") record(f"Remote prefixes: {'PASS' if remote_passed else 'FAIL'}") record(f"IP routing table: {'PASS' if route_passed else 'FAIL'}") record( f"Unexpected prefixes: " f"{len(unexpected_prefixes)}" ) record( f"BGP-004 RESULT: " f"{'PASS' if router_pass else 'FAIL'}" ) except NetmikoAuthenticationException as exc: infrastructure_error = True record("\nINFRASTRUCTURE ERROR: Authentication failed") record(str(exc)) print(f"[ERROR] {router_name}: SSH authentication failed") except NetmikoTimeoutException as exc: infrastructure_error = True record("\nINFRASTRUCTURE ERROR: Connection timeout") record(str(exc)) print(f"[ERROR] {router_name}: SSH timeout") except Exception as exc: infrastructure_error = True record( f"\nEXECUTION ERROR: {type(exc).__name__}: {exc}" ) record(traceback.format_exc()) print(f"[ERROR] {router_name}: {exc}") finally: if connection: try: connection.disconnect() except Exception: pass if infrastructure_error: status = "INFRASTRUCTURE ERROR" else: remote_passed = ( len(remote_results) == len(remote_prefixes) and all( result["present"] and result["best_path"] for result in remote_results.values() ) ) route_passed = ( 'route_results' in locals() and len(route_results) == len(remote_prefixes) and all( result["installed"] for result in route_results.values() ) ) status = ( "PASS" if ( local_result and remote_passed and route_passed and not unexpected_prefixes ) else "FAIL" ) record(f"\nFINAL ROUTER STATUS: {status}") return { "router": router_name, "status": status, "local_prefix": "PASS" if local_result else "FAIL", "remote_prefixes": ( sum( 1 for result in remote_results.values() if result["present"] and result["best_path"] ) ), "expected_remote_prefixes": len(remote_prefixes), "unexpected_prefixes": len(unexpected_prefixes), "log": "\n".join(log) } # ================================================== # 7. 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-004-ROUTE-VERIFICATION-{timestamp}.txt" ) print("=" * 80) print("SP NETWORKING ACADEMY") print("BGP-004 - ROUTE ADVERTISEMENT VERIFICATION") print("=" * 80) print(f"Execution started: {datetime.now()}") print("Test type: READ ONLY") print("Expected remote prefixes per router: 3") all_results = [] all_logs = [] for router_name, details in ROUTERS.items(): result = test_router( router_name, details ) all_results.append(result) all_logs.append(result["log"]) # ---------------------------------------------- # EXECUTION SUMMARY # ---------------------------------------------- passed = sum( 1 for item in all_results if item["status"] == "PASS" ) failed = sum( 1 for item in all_results if item["status"] == "FAIL" ) infrastructure_errors = sum( 1 for item in all_results if item["status"] == "INFRASTRUCTURE ERROR" ) total_remote = sum( item["remote_prefixes"] for item in all_results ) total_expected = sum( item["expected_remote_prefixes"] for item in all_results ) print("\n" + "=" * 80) print("BGP-004 EXECUTION SUMMARY") print("=" * 80) for item in all_results: print( f"{item['router']} | " f"LOCAL: {item['local_prefix']} | " f"REMOTE: {item['remote_prefixes']}/" f"{item['expected_remote_prefixes']} | " f"UNEXPECTED: {item['unexpected_prefixes']} | " f"FINAL: {item['status']}" ) print( f"\nRemote prefixes verified: " f"{total_remote}/{total_expected}" ) print(f"Routers passed: {passed}/4") print(f"Routers failed: {failed}/4") print(f"Infrastructure errors: {infrastructure_errors}/4") # ---------------------------------------------- # SINGLE CONSOLIDATED REPORT # ---------------------------------------------- with report_file.open("w", encoding="utf-8") as report: report.write("SP NETWORKING ACADEMY\n") report.write( "BGP-004 - ROUTE ADVERTISEMENT VERIFICATION\n" ) report.write(f"\nExecution time: {datetime.now()}\n") report.write("\nTest type: READ ONLY\n") report.write("\n" + "=" * 80) report.write("\nEXECUTION SUMMARY\n") report.write("=" * 80 + "\n") for item in all_results: report.write( f"\n{item['router']} | " f"LOCAL: {item['local_prefix']} | " f"REMOTE: {item['remote_prefixes']}/" f"{item['expected_remote_prefixes']} | " f"UNEXPECTED: {item['unexpected_prefixes']} | " f"FINAL: {item['status']}" ) report.write( f"\n\nRemote prefixes verified: " f"{total_remote}/{total_expected}" ) report.write(f"\nRouters passed: {passed}/4") report.write(f"\nRouters failed: {failed}/4") report.write( f"\nInfrastructure errors: {infrastructure_errors}/4" ) report.write( "\n\n" + "=" * 80 + "\nDETAILED ROUTER TEST RESULTS\n" + "\n" + "=" * 80 ) report.write("\n".join(all_logs)) report.write( "\n\n" + "=" * 80 + "\nEND OF REPORT\n" + "=" * 80 + "\n" ) print(f"\nSingle consolidated report: {report_file}") print("=" * 80) return ( 0 if passed == 4 and failed == 0 and infrastructure_errors == 0 and total_remote == total_expected else 1 ) if __name__ == "__main__": sys.exit(main())