#!/usr/bin/env python3 """ SP NETWORKING ACADEMY BGP-003 - NEIGHBOR ESTABLISHMENT VERIFICATION Purpose: 1. Verify all expected BGP neighbors. 2. Verify neighbor session state is Established. 3. Verify remote AS numbers. 4. Capture neighbor uptime. 5. Capture received-prefix counts. 6. Detect unexpected BGP neighbors. 7. Retry session establishment for up to 120 seconds. 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 = 120 POLL_INTERVAL_SECONDS = 5 # ================================================== # 2. EXPECTED BGP NEIGHBORS # ================================================== ROUTERS = { "R1": { "host": "10.0.31.1", "asn": 65001, "neighbors": { "11.1.1.2": 65002, "13.1.1.2": 65001 } }, "R2": { "host": "10.0.32.1", "asn": 65002, "neighbors": { "11.1.1.1": 65001, "12.1.1.2": 65002 } }, "R3": { "host": "10.0.33.1", "asn": 65001, "neighbors": { "13.1.1.1": 65001, "14.1.1.2": 65002 } }, "R4": { "host": "10.0.34.1", "asn": 65002, "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. PARSE BGP SUMMARY # ================================================== def parse_bgp_summary(output): neighbors = {} for line in output.splitlines(): fields = line.split() if not fields: continue try: ipaddress.ip_address(fields[0]) except ValueError: continue # Standard Cisco IOS BGP summary: # Neighbor V AS MsgRcvd MsgSent TblVer # InQ OutQ Up/Down State/PfxRcd if len(fields) < 10: continue neighbor_ip = fields[0] try: remote_as = int(fields[2]) except (ValueError, IndexError): continue state_or_prefix = fields[-1] # Numeric State/PfxRcd means Established. # A value of zero is also Established. established = state_or_prefix.isdigit() if established: received_prefixes = int(state_or_prefix) uptime = fields[-2] session_state = "ESTABLISHED" else: received_prefixes = None uptime = None session_state = state_or_prefix neighbors[neighbor_ip] = { "remote_as": remote_as, "state": session_state, "established": established, "uptime": uptime, "received_prefixes": received_prefixes } return neighbors # ================================================== # 5. VERIFY NEIGHBORS ON EACH ROUTER # ================================================== def test_router(router_name, details): host = details["host"] expected_neighbors = details["neighbors"] connection = None log = [] infrastructure_error = False final_neighbors = {} unexpected_neighbors = set() start_time = time.time() attempt = 0 last_output = "" def record(message): log.append(message) record("\n" + "=" * 80) record("BGP-003 - NEIGHBOR ESTABLISHMENT 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("\nINFRASTRUCTURE CONNECTION: PASS") # ------------------------------------------ # POLL BGP NEIGHBORS # ------------------------------------------ while time.time() - start_time < MAX_WAIT_SECONDS: attempt += 1 print( f"\n[INFO] {router_name}: " f"Checking BGP neighbors - Attempt {attempt}" ) last_output = connection.send_command( "show ip bgp summary", read_timeout=30 ) final_neighbors = parse_bgp_summary(last_output) # Identify unexpected neighbors unexpected_neighbors = ( set(final_neighbors) - set(expected_neighbors) ) # Check every expected neighbor all_established = True for neighbor_ip in expected_neighbors: neighbor = final_neighbors.get(neighbor_ip) if neighbor and neighbor["established"]: print( f"[PASS] {router_name} -> {neighbor_ip}: " f"ESTABLISHED | " f"Prefixes: {neighbor['received_prefixes']}" ) else: all_established = False state = ( neighbor["state"] if neighbor else "NOT FOUND" ) print( f"[WAIT] {router_name} -> {neighbor_ip}: " f"{state}" ) if all_established: break elapsed = int(time.time() - start_time) remaining = MAX_WAIT_SECONDS - elapsed 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) # ------------------------------------------ # FINAL BGP SUMMARY # ------------------------------------------ elapsed = int(time.time() - start_time) record(f"\nVerification attempts: {attempt}") record(f"Total wait time: {elapsed} seconds") record("\nCOMMAND: show ip bgp summary") record(last_output) # ------------------------------------------ # VERIFY EXPECTED NEIGHBORS # ------------------------------------------ established_count = 0 expected_count = len(expected_neighbors) record("\nEXPECTED NEIGHBOR STATUS:") for neighbor_ip, expected_as in expected_neighbors.items(): neighbor = final_neighbors.get(neighbor_ip) if neighbor is None: status = "NOT FOUND" established = False actual_as = "N/A" uptime = "N/A" prefixes = "N/A" else: actual_as = neighbor["remote_as"] established = neighbor["established"] status = neighbor["state"] uptime = neighbor["uptime"] prefixes = neighbor["received_prefixes"] as_correct = actual_as == expected_as session_pass = established and as_correct if session_pass: established_count += 1 line = ( f"{router_name} -> {neighbor_ip} | " f"Expected AS: {expected_as} | " f"Actual AS: {actual_as} | " f"State: {status} | " f"Uptime: {uptime} | " f"Prefixes: {prefixes} | " f"Result: {'PASS' if session_pass else 'FAIL'}" ) record(line) if not established: print( f"[FAIL] {router_name} -> {neighbor_ip}: " f"Session state = {status}" ) elif not as_correct: print( f"[FAIL] {router_name} -> {neighbor_ip}: " f"Expected AS {expected_as}, actual AS {actual_as}" ) else: print( f"[PASS] {router_name} -> {neighbor_ip}: " f"Established, AS {actual_as}, " f"Prefixes {prefixes}" ) # ------------------------------------------ # DETECT UNEXPECTED NEIGHBORS # ------------------------------------------ record("\nUNEXPECTED NEIGHBOR CHECK:") if unexpected_neighbors: for neighbor_ip in sorted(unexpected_neighbors): record(f"UNEXPECTED NEIGHBOR: {neighbor_ip}") print( f"[FAIL] {router_name}: " f"Unexpected neighbor {neighbor_ip}" ) else: record("No unexpected neighbors found") print( f"[PASS] {router_name}: " "No unexpected neighbors" ) # ------------------------------------------ # FINAL ROUTER RESULT # ------------------------------------------ router_pass = ( established_count == expected_count and not unexpected_neighbors ) record( f"\nEstablished neighbors: " f"{established_count}/{expected_count}" ) record( f"Unexpected neighbors: " f"{len(unexpected_neighbors)}" ) record( f"\nBGP-003 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 connection 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: status = ( "PASS" if ( established_count == expected_count and not unexpected_neighbors ) else "FAIL" ) record("\n" + "-" * 80) record(f"FINAL ROUTER RESULT: {status}") record("-" * 80) return { "router": router_name, "status": status, "expected_neighbors": expected_count, "established_neighbors": ( established_count if not infrastructure_error else 0 ), "unexpected_neighbors": len(unexpected_neighbors), "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-003-NEIGHBORS-{timestamp}.txt" ) print("=" * 80) print("SP NETWORKING ACADEMY") print("BGP-003 - NEIGHBOR ESTABLISHMENT VERIFICATION") print("=" * 80) print(f"Execution started: {datetime.now()}") print("Test type: READ ONLY") print("Expected BGP sessions: 8") print(f"Maximum wait: {MAX_WAIT_SECONDS} seconds per router") all_results = [] all_logs = [] # ---------------------------------------------- # EXECUTE TEST ON ALL FOUR ROUTERS # ---------------------------------------------- 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_established = sum( item["established_neighbors"] for item in all_results ) total_expected = sum( item["expected_neighbors"] for item in all_results ) print("\n" + "=" * 80) print("BGP-003 EXECUTION SUMMARY") print("=" * 80) for item in all_results: print( f"{item['router']}: {item['status']} | " f"Neighbors: {item['established_neighbors']}/" f"{item['expected_neighbors']} | " f"Unexpected: {item['unexpected_neighbors']}" ) print( f"\nEstablished sessions: " f"{total_established}/{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-003 - NEIGHBOR ESTABLISHMENT 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']} | " f"Neighbors: {item['established_neighbors']}/" f"{item['expected_neighbors']} | " f"Unexpected: {item['unexpected_neighbors']}" ) report.write( f"\n\nEstablished sessions: " f"{total_established}/{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_established == total_expected else 1 ) if __name__ == "__main__": sys.exit(main())