#!/usr/bin/env python3 """ SP NETWORKING ACADEMY BGP-007 - NEXT-HOP REACHABILITY VERIFICATION Purpose: 1. Verify expected BGP prefixes. 2. Identify the selected best path. 3. Extract the selected path's next-hop. 4. Verify next-hop reachability using show ip route. 5. Generate one consolidated report. Test type: READ ONLY Configuration changes: NONE """ import sys import re from pathlib import Path from datetime import datetime from netmiko import ConnectHandler # -------------------------------------------------- # DIRECTORIES # -------------------------------------------------- BASE_DIR = Path("/home/user/network-automation/BGP") REPORT_DIR = BASE_DIR / "REPORTS" REPORT_DIR.mkdir(parents=True, exist_ok=True) # -------------------------------------------------- # ROUTER DETAILS # -------------------------------------------------- USERNAME = "admin" PASSWORD = "cisco123" ROUTERS = { "R1": { "host": "10.0.31.1", "prefixes": [ "172.16.2.2/32", "172.16.3.3/32", "172.16.4.4/32", ], }, "R2": { "host": "10.0.32.1", "prefixes": [ "172.16.1.1/32", "172.16.3.3/32", "172.16.4.4/32", ], }, "R3": { "host": "10.0.33.1", "prefixes": [ "172.16.1.1/32", "172.16.2.2/32", "172.16.4.4/32", ], }, "R4": { "host": "10.0.34.1", "prefixes": [ "172.16.1.1/32", "172.16.2.2/32", "172.16.3.3/32", ], }, } # Retry route verification if convergence or CLI output # is temporarily delayed. MAX_ATTEMPTS = 3 RETRY_DELAY = 5 # -------------------------------------------------- # DEVICE CONNECTION # -------------------------------------------------- def connect_router(router_name, host): device = { "device_type": "cisco_ios", "host": host, "username": USERNAME, "password": PASSWORD, "conn_timeout": 15, "auth_timeout": 20, "banner_timeout": 20, "fast_cli": False, } print(f"\n[INFO] Connecting to {router_name} ({host})") connection = ConnectHandler(**device) print(f"[PASS] SSH connected to {router_name}") return connection # -------------------------------------------------- # FIND SELECTED BEST-PATH NEXT-HOP # -------------------------------------------------- def extract_best_next_hop(output): # Split BGP output into individual path blocks. blocks = re.split( r"(?=^\s*Refresh Epoch)", output, flags=re.MULTILINE ) for block in blocks: # Only inspect the path explicitly marked best. if not re.search( r"\bvalid\b.*\bbest\b", block, re.IGNORECASE ): continue # Extract the next-hop from THIS best-path block. match = re.search( r"^\s*(\d{1,3}(?:\.\d{1,3}){3})" r"(?:\s+\(inaccessible\))?\s+from\s+", block, re.MULTILINE ) if match: return match.group(1) return None # -------------------------------------------------- # NEXT-HOP ROUTE VERIFICATION # -------------------------------------------------- def verify_next_hop(connection, next_hop): command = f"show ip route {next_hop}" output = connection.send_command( command, read_timeout=30 ) unreachable_patterns = [ "% Network not in table", "% Subnet not in table", "Network not in table", "Subnet not in table", "Route not found", ] if any(pattern.lower() in output.lower() for pattern in unreachable_patterns): return False, output # Cisco IOS normally displays a route entry or # routing-table lookup result when a route exists. route_found = ( "Routing entry for" in output or "Known via" in output or "directly connected" in output.lower() or "via " in output ) return route_found, output # -------------------------------------------------- # MAIN ROUTER TEST # -------------------------------------------------- def test_router(router_name, router_data, report): host = router_data["host"] prefixes = router_data["prefixes"] passed = 0 failed = 0 results = [] connection = None report.write("\n" + "=" * 78 + "\n") report.write( f"BGP-007 - NEXT-HOP REACHABILITY VERIFICATION\n" ) report.write(f"Router: {router_name}\n") report.write(f"Management IP: {host}\n") report.write("=" * 78 + "\n") try: connection = connect_router(router_name, host) for prefix in prefixes: print(f"\n[INFO] {router_name}: Checking {prefix}") report.write(f"\n[INFO] Checking prefix: {prefix}\n") command = f"show ip bgp {prefix}" report.write(f"[INFO] Command: {command}\n") bgp_output = connection.send_command( command, read_timeout=30 ) report.write("\n--- BGP OUTPUT BEGIN ---\n") report.write(bgp_output + "\n") report.write("--- BGP OUTPUT END ---\n") if "Paths:" not in bgp_output: print(f"[FAIL] {router_name}: {prefix} missing") report.write( f"[FAIL] BGP prefix {prefix} not found\n" ) failed += 1 results.append(False) continue next_hop = extract_best_next_hop(bgp_output) if not next_hop: print( f"[FAIL] {router_name}: " f"Best-path next-hop not identified" ) report.write( "[FAIL] Could not identify selected best-path next-hop\n" ) failed += 1 results.append(False) continue print( f"[PASS] {router_name}: {prefix} " f"| Best next-hop = {next_hop}" ) report.write( f"[PASS] Best-path next-hop identified: {next_hop}\n" ) # Locally sourced route. if next_hop == "0.0.0.0": print( f"[PASS] {router_name}: " "Locally sourced BGP prefix" ) report.write( "[PASS] Local BGP route - no remote next-hop lookup required\n" ) passed += 1 results.append(True) continue reachable = False for attempt in range(1, MAX_ATTEMPTS + 1): print( f"[INFO] {router_name}: " f"Next-hop verification attempt {attempt}" ) report.write( f"[INFO] Next-hop verification attempt {attempt}\n" ) route_ok, route_output = verify_next_hop( connection, next_hop ) report.write( f"\n--- ROUTE LOOKUP: {next_hop} ---\n" ) report.write(route_output + "\n") report.write("--- ROUTE LOOKUP END ---\n") if route_ok: reachable = True break if attempt < MAX_ATTEMPTS: import time time.sleep(RETRY_DELAY) if reachable: print( f"[PASS] {router_name}: " f"Next-hop {next_hop} is reachable" ) report.write( f"[PASS] Next-hop {next_hop} is reachable\n" ) passed += 1 results.append(True) else: print( f"[FAIL] {router_name}: " f"Next-hop {next_hop} is unreachable" ) report.write( f"[FAIL] Next-hop {next_hop} is unreachable\n" ) failed += 1 results.append(False) final_status = "PASS" if failed == 0 else "FAIL" except Exception as error: print(f"[ERROR] {router_name}: {error}") report.write(f"\n[ERROR] {str(error)}\n") final_status = "FAIL" # A router-level exception invalidates the router test. failed = max(failed, len(prefixes) - passed) finally: if connection: connection.disconnect() print(f"[INFO] Disconnected from {router_name}") report.write("[INFO] Disconnected from router\n") report.write(f"\n{router_name} SUMMARY\n") report.write(f"Prefixes tested: {len(prefixes)}\n") report.write(f"Next-hops passed: {passed}\n") report.write(f"Next-hops failed: {failed}\n") report.write(f"FINAL STATUS: {final_status}\n") return { "router": router_name, "host": host, "passed": passed, "failed": failed, "status": final_status, } # -------------------------------------------------- # MAIN EXECUTION # -------------------------------------------------- def main(): timestamp = datetime.now().strftime("%Y%m%d_%H%M%S") report_file = ( REPORT_DIR / f"BGP-007-NEXT-HOP-{timestamp}.txt" ) router_results = [] print("\n" + "=" * 78) print("SP NETWORKING ACADEMY - BGP-007") print("NEXT-HOP REACHABILITY VERIFICATION") print("=" * 78) print("Password authentication: Automatic") print("Test type: READ ONLY") print("Configuration changes: NONE") with report_file.open("w", encoding="utf-8") as report: report.write("=" * 78 + "\n") report.write( "SP NETWORKING ACADEMY - BGP-007\n" ) report.write( "NEXT-HOP REACHABILITY VERIFICATION\n" ) report.write("=" * 78 + "\n") report.write( f"Execution started: {datetime.now()}\n" ) report.write("Test type: READ ONLY\n") report.write("Configuration changes: NONE\n") report.write("Password authentication: Automatic\n") for router_name, router_data in ROUTERS.items(): result = test_router( router_name, router_data, report ) router_results.append(result) # FINAL SUMMARY routers_passed = sum( 1 for item in router_results if item["status"] == "PASS" ) routers_failed = 4 - routers_passed total_passed = sum( item["passed"] for item in router_results ) total_failed = sum( item["failed"] for item in router_results ) report.write("\n" + "=" * 78 + "\n") report.write("BGP-007 EXECUTION SUMMARY\n") report.write("=" * 78 + "\n") print("\n" + "=" * 78) print("BGP-007 EXECUTION SUMMARY") print("=" * 78) for item in router_results: summary = ( f'{item["router"]} ({item["host"]}) | ' f'PASS: {item["passed"]} | ' f'FAIL: {item["failed"]} | ' f'FINAL: {item["status"]}' ) print(summary) report.write(summary + "\n") report.write(f"\nNext-hop checks passed: {total_passed}\n") report.write(f"Next-hop checks failed: {total_failed}\n") report.write(f"Routers passed: {routers_passed}/4\n") report.write(f"Routers failed: {routers_failed}/4\n") print(f"\nNext-hop checks passed: {total_passed}") print(f"Next-hop checks failed: {total_failed}") print(f"Routers passed: {routers_passed}/4") print(f"Routers failed: {routers_failed}/4") report.write("\nSingle consolidated report:\n") report.write(str(report_file) + "\n") print("\nSingle consolidated report:") print(report_file) print("=" * 78) return 0 if total_failed == 0 and routers_failed == 0 else 1 if __name__ == "__main__": sys.exit(main())