#!/usr/bin/env python3 """ SP NETWORKING ACADEMY BGP-002 - BGP PROCESS CONFIGURATION VERIFICATION Purpose: 1. Verify BGP local AS. 2. Verify BGP router ID. 3. Verify network advertisement statements. 4. Verify BGP neighbor IP addresses. 5. Verify neighbor remote-AS values. 6. Detect unexpected BGP neighbors and network statements. Read-only test. Single consolidated report. """ from datetime import datetime from pathlib import Path import ipaddress import re import sys 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" # ================================================== # 2. EXPECTED BGP CONFIGURATION # ================================================== ROUTERS = { "R1": { "host": "10.0.31.1", "asn": 65001, "router_id": "1.1.1.1", "networks": { ("172.16.1.1", "255.255.255.255") }, "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", "networks": { ("172.16.2.2", "255.255.255.255") }, "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", "networks": { ("172.16.3.3", "255.255.255.255") }, "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", "networks": { ("172.16.4.4", "255.255.255.255") }, "neighbors": { "12.1.1.1": 65002, "14.1.1.1": 65001 } } } # ================================================== # 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. CONFIGURATION PARSING # ================================================== def parse_networks(config): networks = set() for line in config.splitlines(): match = re.match( r"^\s*network\s+(\d+\.\d+\.\d+\.\d+)" r"\s+mask\s+(\d+\.\d+\.\d+\.\d+)\s*$", line ) if match: networks.add(( match.group(1), match.group(2) )) return networks def parse_neighbors(config): neighbors = {} for line in config.splitlines(): match = re.match( r"^\s*neighbor\s+(\d+\.\d+\.\d+\.\d+)" r"\s+remote-as\s+(\d+)\s*$", line ) if match: neighbors[match.group(1)] = int(match.group(2)) return neighbors def parse_router_id(config): match = re.search( r"(?m)^\s*bgp router-id\s+(\d+\.\d+\.\d+\.\d+)\s*$", config ) return match.group(1) if match else None def parse_local_as(config): match = re.search( r"(?m)^router bgp\s+(\d+)\s*$", config ) return int(match.group(1)) if match else None # ================================================== # 5. ROUTER CONFIGURATION TEST # ================================================== def test_router(router_name, details): host = details["host"] expected_asn = details["asn"] expected_router_id = details["router_id"] expected_networks = details["networks"] expected_neighbors = details["neighbors"] connection = None log = [] results = { "process": False, "asn": False, "router_id": False, "networks": False, "neighbors": False } infrastructure_error = False def record(message): log.append(message) def print_result(label, passed, detail=""): status = "PASS" if passed else "FAIL" message = f"[{status}] {router_name}: {label}" if detail: message += f" | {detail}" print(message) record(message) record("\n" + "=" * 80) record("BGP-002 - BGP PROCESS CONFIGURATION 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") # ------------------------------------------ # COLLECT BGP CONFIGURATION # ------------------------------------------ print(f"[INFO] {router_name}: Collecting BGP configuration") config = connection.send_command( "show running-config | section ^router bgp", read_timeout=30 ) record("\nCOMMAND: show running-config | section ^router bgp") record(config if config else "") # ------------------------------------------ # CHECK BGP PROCESS # ------------------------------------------ actual_asn = parse_local_as(config) results["process"] = actual_asn is not None print_result( "BGP process", results["process"], f"Actual AS = {actual_asn}" ) # ------------------------------------------ # CHECK LOCAL AS # ------------------------------------------ results["asn"] = actual_asn == expected_asn print_result( "Local AS", results["asn"], f"Expected = {expected_asn}, Actual = {actual_asn}" ) # ------------------------------------------ # CHECK ROUTER ID # ------------------------------------------ actual_router_id = parse_router_id(config) results["router_id"] = ( actual_router_id == expected_router_id ) print_result( "BGP router ID", results["router_id"], f"Expected = {expected_router_id}, " f"Actual = {actual_router_id}" ) # ------------------------------------------ # CHECK NETWORK ADVERTISEMENTS # ------------------------------------------ actual_networks = parse_networks(config) missing_networks = expected_networks - actual_networks unexpected_networks = actual_networks - expected_networks results["networks"] = ( not missing_networks and not unexpected_networks ) record("\nNETWORK CONFIGURATION VERIFICATION") record(f"Expected networks: {sorted(expected_networks)}") record(f"Actual networks: {sorted(actual_networks)}") record(f"Missing networks: {sorted(missing_networks)}") record(f"Unexpected networks: {sorted(unexpected_networks)}") print_result( "Network advertisements", results["networks"], f"Expected = {len(expected_networks)}, " f"Actual = {len(actual_networks)}" ) for network in sorted(missing_networks): print(f"[FAIL] {router_name}: Missing network {network}") for network in sorted(unexpected_networks): print(f"[FAIL] {router_name}: Unexpected network {network}") # ------------------------------------------ # CHECK BGP NEIGHBORS AND REMOTE AS # ------------------------------------------ actual_neighbors = parse_neighbors(config) missing_neighbors = ( set(expected_neighbors) - set(actual_neighbors) ) unexpected_neighbors = ( set(actual_neighbors) - set(expected_neighbors) ) wrong_remote_as = { neighbor: { "expected": expected_neighbors[neighbor], "actual": actual_neighbors[neighbor] } for neighbor in set(expected_neighbors) & set(actual_neighbors) if expected_neighbors[neighbor] != actual_neighbors[neighbor] } results["neighbors"] = ( not missing_neighbors and not unexpected_neighbors and not wrong_remote_as ) record("\nBGP NEIGHBOR CONFIGURATION VERIFICATION") record(f"Expected neighbors: {expected_neighbors}") record(f"Actual neighbors: {actual_neighbors}") record(f"Missing neighbors: {sorted(missing_neighbors)}") record(f"Unexpected neighbors: {sorted(unexpected_neighbors)}") record(f"Incorrect remote-AS: {wrong_remote_as}") for neighbor, expected_remote_as in expected_neighbors.items(): actual_remote_as = actual_neighbors.get(neighbor) if actual_remote_as == expected_remote_as: print( f"[PASS] {router_name}: Neighbor {neighbor} " f"remote-AS {actual_remote_as}" ) elif actual_remote_as is None: print( f"[FAIL] {router_name}: " f"Neighbor {neighbor} missing" ) else: print( f"[FAIL] {router_name}: Neighbor {neighbor} " f"expected remote-AS {expected_remote_as}, " f"actual {actual_remote_as}" ) for neighbor in sorted(unexpected_neighbors): print( f"[FAIL] {router_name}: " f"Unexpected neighbor {neighbor}" ) print_result( "BGP neighbor configuration", results["neighbors"], f"Expected = {len(expected_neighbors)}, " f"Actual = {len(actual_neighbors)}" ) 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 # ---------------------------------------------- # FINAL ROUTER STATUS # ---------------------------------------------- test_pass = ( all(results.values()) and not infrastructure_error ) if infrastructure_error: status = "INFRASTRUCTURE ERROR" elif test_pass: status = "PASS" else: status = "FAIL" record("\n" + "-" * 80) record(f"BGP-002 RESULT: {status}") record("-" * 80) return { "router": router_name, "status": status, "results": results, "log": "\n".join(log) } # ================================================== # 6. 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-002-PROCESS-CONFIG-{timestamp}.txt" ) print("=" * 80) print("SP NETWORKING ACADEMY") print("BGP-002 - BGP PROCESS CONFIGURATION VERIFICATION") print("=" * 80) print(f"Execution started: {datetime.now()}") print("Test type: READ ONLY") print("Routers under test: 4") 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" ) print("\n" + "=" * 80) print("BGP-002 EXECUTION SUMMARY") print("=" * 80) for item in all_results: print(f"{item['router']}: {item['status']}") print(f"\nRouters 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-002 - BGP PROCESS CONFIGURATION 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']}: {item['status']}" ) report.write(f"\n\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 else 1 ) if __name__ == "__main__": sys.exit(main())