#!/usr/bin/env python3 """ SP NETWORKING ACADEMY BGP-006 - BGP PATH ATTRIBUTE VERIFICATION Read-only verification across R1-R4. Attributes: - LOCAL_PREF - AS_PATH - ORIGIN - MED - NEXT_HOP - Path type - Best-path identification No configuration changes are performed. """ import re import sys from datetime import datetime from pathlib import Path from netmiko import ConnectHandler # ================================================== # 1. 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.31.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, } # ================================================== # 2. REPORTING # ================================================== timestamp = datetime.now().strftime("%Y%m%d_%H%M%S") REPORT_FILE = ( REPORT_DIR / f"BGP-006-ATTRIBUTE-VERIFICATION-{timestamp}.txt" ) REPORT_LINES = [] def log(message=""): print(message) REPORT_LINES.append(str(message)) # ================================================== # 3. SSH CONNECTION # ================================================== def connect_router(host): device = { "device_type": DEVICE_TYPE, "host": host, "username": USERNAME, "password": PASSWORD, **CONNECT_PARAMS, } return ConnectHandler(**device) # ================================================== # 4. PARSE PATH ATTRIBUTE INFORMATION # ================================================== def parse_bgp_paths(output): """ Parse Cisco IOS detailed output from: show ip bgp Typical output: Paths: (2 available, best #2, table default) Refresh Epoch 1 65002 14.1.1.2 from 13.1.1.2 (3.3.3.3) Origin IGP, metric 0, localpref 100, valid, internal Refresh Epoch 1 65002 11.1.1.2 from 11.1.1.2 (2.2.2.2) Origin IGP, metric 0, localpref 100, valid, external, best """ header = re.search( r"Paths:\s*\((\d+)\s+available,\s*best\s+#(\d+)", output, re.IGNORECASE, ) if not header: return None available_paths = int(header.group(1)) best_number = int(header.group(2)) blocks = re.split( r"(?=^\s*Refresh Epoch)", output, flags=re.MULTILINE, ) paths = [] for block in blocks: if not re.search(r"^\s*Refresh Epoch", block, re.MULTILINE): continue # AS_PATH is generally displayed on a separate # line immediately before the next-hop line. as_path = "Not displayed" as_match = re.search( r"^\s*(Local|\d+(?:\s+\d+)*)\s*$", block, re.MULTILINE, ) if as_match: as_path = as_match.group(1) next_hop_match = re.search( r"^\s*(\d+\.\d+\.\d+\.\d+)" r"(?:\s+\((inaccessible)\))?" r"\s+from\s+" r"(\d+\.\d+\.\d+\.\d+)" r"\s+\((\d+\.\d+\.\d+\.\d+)\)", block, re.MULTILINE, ) next_hop = ( next_hop_match.group(1) if next_hop_match else "Not displayed" ) inaccessible = ( bool(next_hop_match and next_hop_match.group(2)) ) peer = ( next_hop_match.group(3) if next_hop_match else "Not displayed" ) peer_router_id = ( next_hop_match.group(4) if next_hop_match else "Not displayed" ) origin_match = re.search( r"\bOrigin\s+(IGP|EGP|incomplete)\b", block, re.IGNORECASE, ) origin = ( origin_match.group(1).upper() if origin_match else "Not displayed" ) metric_match = re.search( r"\bmetric\s+(\d+)", block, re.IGNORECASE, ) med = ( metric_match.group(1) if metric_match else "Not advertised/displayed" ) localpref_match = re.search( r"\blocalpref\s+(\d+)", block, re.IGNORECASE, ) localpref = ( localpref_match.group(1) if localpref_match else "Not displayed" ) if re.search(r"\bexternal\b", block, re.IGNORECASE): path_type = "eBGP" elif re.search(r"\binternal\b", block, re.IGNORECASE): path_type = "iBGP" elif as_path == "Local": path_type = "LOCAL" else: path_type = "UNKNOWN" is_valid = bool( re.search(r"\bvalid\b", block, re.IGNORECASE) ) is_best = bool( re.search(r"\bbest\b", block, re.IGNORECASE) ) paths.append({ "as_path": as_path, "next_hop": next_hop, "inaccessible": inaccessible, "peer": peer, "peer_router_id": peer_router_id, "origin": origin, "med": med, "localpref": localpref, "path_type": path_type, "valid": is_valid, "best": is_best, }) # The detailed output's best #N identifies the # selected path in the displayed path ordering. # Cross-check the parsed best marker as well. best_index_valid = ( 1 <= best_number <= available_paths ) return { "available": available_paths, "best_number": best_number, "best_index_valid": best_index_valid, "paths": paths, } # ================================================== # 5. ATTRIBUTE REPORT # ================================================== def report_path_attributes(router, prefix, parsed): log(f"\n[INFO] {router}: ATTRIBUTE DETAILS FOR {prefix}") log(f"Available paths: {parsed['available']}") log(f"Best path number: {parsed['best_number']}") for index, path in enumerate(parsed["paths"], start=1): log(f"\nPATH {index}") log(f" AS_PATH : {path['as_path']}") log(f" NEXT_HOP : {path['next_hop']}") log( f" NEXT_HOP STATE: " f"{'INACCESSIBLE' if path['inaccessible'] else 'Not flagged inaccessible'}" ) log(f" PEER : {path['peer']}") log(f" PEER ROUTER ID: {path['peer_router_id']}") log(f" LOCAL_PREF : {path['localpref']}") log(f" MED : {path['med']}") log(f" ORIGIN : {path['origin']}") log(f" PATH TYPE : {path['path_type']}") log(f" VALID : {path['valid']}") log(f" BEST : {path['best']}") # ================================================== # 6. ROUTER TEST # ================================================== def test_router(router_name, router_data): host = router_data["host"] expected_prefixes = router_data["expected_prefixes"] connection = None present = 0 best_identified = 0 attribute_paths = 0 inaccessible_paths = 0 router_failed = False log("\n" + "=" * 80) log("BGP-006 - PATH ATTRIBUTE VERIFICATION") log(f"Router: {router_name}") log(f"Management IP: {host}") log("=" * 80) try: log(f"\n[INFO] Connecting to {router_name} ({host})") connection = connect_router(host) log(f"[PASS] SSH connected to {router_name}") for prefix in expected_prefixes: log(f"\n[INFO] {router_name}: Checking {prefix}") command = f"show ip bgp {prefix}" output = connection.send_command( command, read_timeout=30, ) log(f"[INFO] Command: {command}") log("\n--- DEVICE OUTPUT BEGIN ---") log(output) log("--- DEVICE OUTPUT END ---") parsed = parse_bgp_paths(output) if parsed is None: log( f"[FAIL] {router_name}: " f"Could not parse BGP path information for {prefix}" ) router_failed = True continue if parsed["available"] != len(parsed["paths"]): log( f"[FAIL] {router_name}: " f"Path count mismatch for {prefix}. " f"Header={parsed['available']}, " f"Parsed={len(parsed['paths'])}" ) router_failed = True continue if not parsed["best_index_valid"]: log( f"[FAIL] {router_name}: " f"Invalid best path index for {prefix}" ) router_failed = True continue if not any(path["best"] for path in parsed["paths"]): log( f"[FAIL] {router_name}: " f"No best path marker for {prefix}" ) router_failed = True continue present += 1 best_identified += 1 log( f"[PASS] {router_name}: {prefix} " f"| Paths={parsed['available']} " f"| Best=#{parsed['best_number']}" ) report_path_attributes( router_name, prefix, parsed, ) for path in parsed["paths"]: attribute_paths += 1 if path["inaccessible"]: inaccessible_paths += 1 # Attribute fields are recorded even when # the router does not display an optional # attribute such as MED. if path["as_path"] == "Not displayed": log("[WARN] AS_PATH not extracted from this path") if path["next_hop"] == "Not displayed": log("[WARN] NEXT_HOP not extracted from this path") if path["origin"] == "Not displayed": log("[WARN] ORIGIN not extracted from this path") except Exception as error: router_failed = True log( f"[ERROR] {router_name}: " f"{type(error).__name__}: {error}" ) finally: if connection: try: connection.disconnect() log(f"[INFO] Disconnected from {router_name}") except Exception: pass expected_count = len(expected_prefixes) final_status = ( "PASS" if not router_failed and present == expected_count and best_identified == expected_count else "FAIL" ) log(f"\n{router_name} ATTRIBUTE SUMMARY") log(f"Prefixes verified: {present}/{expected_count}") log(f"Best paths identified: {best_identified}/{expected_count}") log(f"Path records collected: {attribute_paths}") log(f"Inaccessible next-hops observed: {inaccessible_paths}") log(f"FINAL STATUS: {final_status}") return { "router": router_name, "prefixes": present, "expected": expected_count, "best": best_identified, "attribute_paths": attribute_paths, "inaccessible": inaccessible_paths, "status": final_status, } # ================================================== # 7. MAIN EXECUTION # ================================================== def main(): results = [] log("=" * 80) log("SP NETWORKING ACADEMY") log("BGP-006 - BGP PATH ATTRIBUTE VERIFICATION") log("=" * 80) log(f"Execution started: {datetime.now()}") log("Test type: READ ONLY") log("Configuration changes: NONE") log("Password authentication: Automatic") log("\nAttributes collected:") log("AS_PATH | NEXT_HOP | LOCAL_PREF | MED | ORIGIN | PATH TYPE") for router_name, router_data in ROUTERS.items(): result = test_router( router_name, router_data, ) results.append(result) # ------------------------------------------------ # FINAL SUMMARY # ------------------------------------------------ routers_passed = sum( 1 for item in results if item["status"] == "PASS" ) routers_failed = len(results) - routers_passed total_prefixes = sum( item["prefixes"] for item in results ) total_expected = sum( item["expected"] for item in results ) total_best = sum( item["best"] for item in results ) total_attribute_paths = sum( item["attribute_paths"] for item in results ) total_inaccessible = sum( item["inaccessible"] for item in results ) log("\n" + "=" * 80) log("BGP-006 EXECUTION SUMMARY") log("=" * 80) for item in results: log( f"{item['router']} | " f"PREFIXES: {item['prefixes']}/{item['expected']} | " f"BEST: {item['best']}/{item['expected']} | " f"ATTRIBUTE PATHS: {item['attribute_paths']} | " f"INACCESSIBLE: {item['inaccessible']} | " f"FINAL: {item['status']}" ) log(f"\nPrefixes verified: {total_prefixes}/{total_expected}") log(f"Best paths identified: {total_best}/{total_expected}") log(f"Attribute path records collected: {total_attribute_paths}") log(f"Inaccessible next-hops observed: {total_inaccessible}") log(f"Routers passed: {routers_passed}/4") log(f"Routers failed: {routers_failed}/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(REPORT_LINES)) report.write("\n") print(f"\n[INFO] Report saved: {REPORT_FILE}") return 0 if routers_passed == 4 else 1 if __name__ == "__main__": sys.exit(main())