#!/usr/bin/env python3 """ SP NETWORKING ACADEMY BGP-005 - BEST-PATH SELECTION VERIFICATION Purpose: 1. Verify expected remote BGP prefixes. 2. Identify available paths for each prefix. 3. Verify that a best path is selected. 4. Record the detailed BGP output. 5. Generate one consolidated report. READ-ONLY TEST: No router configuration changes. No BGP neighbor resets. """ import re import sys from datetime import datetime from pathlib import Path from netmiko import ConnectHandler # -------------------------------------------------- # CONFIGURATION # -------------------------------------------------- BASE_DIR = Path("/home/user/network-automation/BGP") REPORT_DIR = BASE_DIR / "REPORTS" REPORT_DIR.mkdir(parents=True, exist_ok=True) USERNAME = "admin" PASSWORD = "cisco123" ROUTERS = { "R1": { "host": "10.0.31.1", "expected_prefixes": [ "172.16.2.2/32", "172.16.3.3/32", "172.16.4.4/32", ], }, "R2": { "host": "10.0.32.1", "expected_prefixes": [ "172.16.1.1/32", "172.16.3.3/32", "172.16.4.4/32", ], }, "R3": { "host": "10.0.33.1", "expected_prefixes": [ "172.16.1.1/32", "172.16.2.2/32", "172.16.4.4/32", ], }, "R4": { "host": "10.0.34.1", "expected_prefixes": [ "172.16.1.1/32", "172.16.2.2/32", "172.16.3.3/32", ], }, } DEVICE_TYPE = "cisco_ios" CONNECT_PARAMS = { "conn_timeout": 15, "auth_timeout": 20, "banner_timeout": 20, "fast_cli": False, } # -------------------------------------------------- # REPORT AND SUMMARY DATA # -------------------------------------------------- timestamp = datetime.now().strftime("%Y%m%d_%H%M%S") report_file = REPORT_DIR / f"BGP-005-BEST-PATH-{timestamp}.txt" results = {} all_results = [] total_prefixes = 0 total_present = 0 total_best = 0 total_multiple = 0 routers_passed = 0 routers_failed = 0 infrastructure_errors = 0 def log(message=""): """Print to terminal and append to consolidated report.""" print(message) all_results.append(str(message)) def verify_prefix(output): """ Verify a single-prefix 'show ip bgp ' response. Cisco IOS detailed output normally contains: Paths: (N available, best #X, table default) This avoids parsing wrapped rows in the complete BGP table. """ if "Network not in table" in output: return { "present": False, "paths": 0, "best": False, "best_details": [], } match = re.search( r"Paths:\s*\((\d+)\s+available,\s*best\s+#(\d+)", output, re.IGNORECASE, ) if not match: return { "present": False, "paths": 0, "best": False, "best_details": [], } path_count = int(match.group(1)) best_number = int(match.group(2)) # The IOS detailed entry identifies the selected path # using the "best" keyword in its path attributes. best_lines = [ line.strip() for line in output.splitlines() if re.search(r"\bvalid\b", line, re.IGNORECASE) and re.search(r"\bbest\b", line, re.IGNORECASE) ] best_identified = ( path_count > 0 and 1 <= best_number <= path_count and len(best_lines) > 0 ) return { "present": path_count > 0, "paths": path_count, "best": best_identified, "best_details": best_lines, } def test_router(router_name, router_data): global total_prefixes global total_present global total_best global total_multiple global infrastructure_errors host = router_data["host"] expected_prefixes = router_data["expected_prefixes"] router_prefixes = 0 router_best = 0 router_multiple = 0 router_failed = False log("\n" + "=" * 80) log(f"BGP-005 - BEST-PATH VERIFICATION") log(f"Router: {router_name}") log(f"Management IP: {host}") log("=" * 80) device = { "device_type": DEVICE_TYPE, "host": host, "username": USERNAME, "password": PASSWORD, **CONNECT_PARAMS, } connection = None try: log(f"\n[INFO] Connecting to {router_name} ({host})") connection = ConnectHandler(**device) log(f"[PASS] SSH connected to {router_name}") for prefix in expected_prefixes: total_prefixes += 1 log(f"\n[INFO] {router_name}: Checking {prefix}") command = f"show ip bgp {prefix}" log(f"[INFO] Command: {command}") output = connection.send_command( command, read_timeout=30, ) log("\n--- DEVICE OUTPUT BEGIN ---") log(output) log("--- DEVICE OUTPUT END ---") verification = verify_prefix(output) if not verification["present"]: log(f"[FAIL] {router_name}: {prefix} missing") router_failed = True continue router_prefixes += 1 total_present += 1 path_count = verification["paths"] log( f"[PASS] {router_name}: {prefix} present " f"| Available paths: {path_count}" ) if verification["best"]: router_best += 1 total_best += 1 log( f"[PASS] {router_name}: " f"{prefix} best path identified" ) for detail in verification["best_details"]: log(f"[INFO] Best-path attributes: {detail}") else: log( f"[FAIL] {router_name}: " f"{prefix} best path not identified" ) router_failed = True if path_count > 1: router_multiple += 1 total_multiple += 1 log( f"[INFO] {router_name}: {prefix} " f"has {path_count} available paths" ) final_status = ( not router_failed and router_prefixes == len(expected_prefixes) and router_best == len(expected_prefixes) ) results[router_name] = { "prefixes": router_prefixes, "expected": len(expected_prefixes), "best": router_best, "multiple": router_multiple, "status": "PASS" if final_status else "FAIL", } except Exception as error: infrastructure_errors += 1 router_failed = True log(f"[ERROR] {router_name}: {type(error).__name__}: {error}") results[router_name] = { "prefixes": router_prefixes, "expected": len(expected_prefixes), "best": router_best, "multiple": router_multiple, "status": "ERROR", } finally: if connection: connection.disconnect() log(f"[INFO] Disconnected from {router_name}") # -------------------------------------------------- # MAIN EXECUTION # -------------------------------------------------- def main(): global routers_passed global routers_failed log("=" * 80) log("SP NETWORKING ACADEMY") log("BGP-005 - BEST-PATH SELECTION VERIFICATION") log("=" * 80) log(f"Execution time: {datetime.now()}") log("Test type: READ ONLY") log("Configuration changes: NONE") log("Password authentication: Automatic") for router_name, router_data in ROUTERS.items(): test_router(router_name, router_data) # -------------------------------------------------- # FINAL SUMMARY # -------------------------------------------------- log("\n" + "=" * 80) log("BGP-005 EXECUTION SUMMARY") log("=" * 80) for router_name in ROUTERS: result = results.get(router_name) if result is None: routers_failed += 1 log(f"{router_name} | FINAL: ERROR") continue if result["status"] == "PASS": routers_passed += 1 else: routers_failed += 1 log( f"{router_name} | " f"PREFIXES: {result['prefixes']}/{result['expected']} | " f"BEST PATHS: {result['best']}/{result['expected']} | " f"MULTIPLE PATHS: {result['multiple']} | " f"FINAL: {result['status']}" ) log(f"\nPrefixes present: {total_present}/{total_prefixes}") log(f"Best paths identified: {total_best}/{total_prefixes}") log(f"Prefixes with multiple paths: {total_multiple}") log(f"Routers passed: {routers_passed}/4") log(f"Routers failed: {routers_failed}/4") log(f"Infrastructure errors: {infrastructure_errors}/4") log("\nSingle consolidated report:") log(str(report_file)) log("=" * 80) with report_file.open("w", encoding="utf-8") as report: report.write("\n".join(all_results)) report.write("\n") print(f"\n[INFO] Report saved: {report_file}") return 0 if routers_failed == 0 else 1 if __name__ == "__main__": sys.exit(main())