#!/usr/bin/env python3 """ SP NETWORKING ACADEMY BGP-001 - ROUTER IDENTITY AND AS VERIFICATION Purpose: 1. Verify router hostname. 2. Verify local BGP AS number. 3. Verify BGP router ID. 4. Validate all four routers against the approved lab design. Read-only test. No configuration changes. One consolidated execution report. """ from datetime import datetime from pathlib import Path 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 ROUTER DETAILS # ================================================== ROUTERS = { "R1": { "host": "10.0.31.1", "hostname": "R1", "asn": 65001, "router_id": "1.1.1.1" }, "R2": { "host": "10.0.32.1", "hostname": "R2", "asn": 65002, "router_id": "2.2.2.2" }, "R3": { "host": "10.0.33.1", "hostname": "R3", "asn": 65001, "router_id": "3.3.3.3" }, "R4": { "host": "10.0.34.1", "hostname": "R4", "asn": 65002, "router_id": "4.4.4.4" } } # ================================================== # 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. VERIFY ROUTER IDENTITY AND BGP AS # ================================================== def test_router(router_name, details): host = details["host"] expected_hostname = details["hostname"] expected_asn = details["asn"] expected_router_id = details["router_id"] log = [] log.append("\n" + "=" * 80) log.append(f"BGP-001 - ROUTER IDENTITY AND AS VERIFICATION") log.append(f"Router: {router_name}") log.append(f"Management IP: {host}") log.append("=" * 80) connection = None results = { "hostname": False, "asn": False, "router_id": False } infrastructure_error = False try: print(f"\n[INFO] Connecting to {router_name} ({host})") connection = create_connection(host) print(f"[PASS] SSH connected to {router_name}") log.append("\nINFRASTRUCTURE CONNECTION: PASS") # ------------------------------------------ # CHECK HOSTNAME # ------------------------------------------ print(f"[INFO] {router_name}: Checking hostname") hostname_output = connection.send_command( "show running-config | include ^hostname" ) log.append("\nCOMMAND: show running-config | include ^hostname") log.append(hostname_output) hostname_match = re.search( r"(?m)^hostname\s+(\S+)", hostname_output ) actual_hostname = ( hostname_match.group(1) if hostname_match else None ) results["hostname"] = ( actual_hostname == expected_hostname ) if results["hostname"]: print( f"[PASS] {router_name}: " f"Hostname = {actual_hostname}" ) else: print( f"[FAIL] {router_name}: " f"Expected hostname {expected_hostname}, " f"found {actual_hostname}" ) log.append( f"\nHOSTNAME TEST: " f"{'PASS' if results['hostname'] else 'FAIL'}" ) log.append(f"Expected: {expected_hostname}") log.append(f"Actual: {actual_hostname}") # ------------------------------------------ # CHECK BGP CONFIGURATION # ------------------------------------------ print(f"[INFO] {router_name}: Checking BGP configuration") bgp_config = connection.send_command( "show running-config | section ^router bgp" ) log.append( "\nCOMMAND: show running-config | section ^router bgp" ) log.append(bgp_config) # ------------------------------------------ # CHECK LOCAL AS NUMBER # ------------------------------------------ as_match = re.search( r"(?m)^router bgp\s+(\d+)", bgp_config ) actual_asn = ( int(as_match.group(1)) if as_match else None ) results["asn"] = actual_asn == expected_asn if results["asn"]: print( f"[PASS] {router_name}: " f"Local AS = {actual_asn}" ) else: print( f"[FAIL] {router_name}: " f"Expected AS {expected_asn}, " f"found {actual_asn}" ) log.append( f"\nLOCAL AS TEST: " f"{'PASS' if results['asn'] else 'FAIL'}" ) log.append(f"Expected AS: {expected_asn}") log.append(f"Actual AS: {actual_asn}") # ------------------------------------------ # CHECK BGP ROUTER ID # ------------------------------------------ print(f"[INFO] {router_name}: Checking BGP router ID") bgp_summary = connection.send_command( "show ip bgp summary" ) log.append("\nCOMMAND: show ip bgp summary") log.append(bgp_summary) router_id_match = re.search( r"BGP router identifier\s+(\d+\.\d+\.\d+\.\d+)", bgp_summary, re.IGNORECASE ) actual_router_id = ( router_id_match.group(1) if router_id_match else None ) results["router_id"] = ( actual_router_id == expected_router_id ) if results["router_id"]: print( f"[PASS] {router_name}: " f"Router ID = {actual_router_id}" ) else: print( f"[FAIL] {router_name}: " f"Expected router ID {expected_router_id}, " f"found {actual_router_id}" ) log.append( f"\nROUTER ID TEST: " f"{'PASS' if results['router_id'] else 'FAIL'}" ) log.append(f"Expected Router ID: {expected_router_id}") log.append(f"Actual Router ID: {actual_router_id}") except NetmikoAuthenticationException as exc: infrastructure_error = True log.append(f"\nINFRASTRUCTURE ERROR: Authentication failed") log.append(str(exc)) print(f"[ERROR] {router_name}: SSH authentication failed") except NetmikoTimeoutException as exc: infrastructure_error = True log.append(f"\nINFRASTRUCTURE ERROR: Connection timeout") log.append(str(exc)) print(f"[ERROR] {router_name}: SSH connection timeout") except Exception as exc: infrastructure_error = True log.append( f"\nEXECUTION ERROR: {type(exc).__name__}: {exc}" ) log.append(traceback.format_exc()) print(f"[ERROR] {router_name}: {exc}") finally: if connection: try: connection.disconnect() except Exception: pass # ---------------------------------------------- # ROUTER TEST RESULT # ---------------------------------------------- test_pass = ( all(results.values()) and not infrastructure_error ) if infrastructure_error: status = "INFRASTRUCTURE ERROR" elif test_pass: status = "PASS" else: status = "FAIL" log.append("\n" + "-" * 80) log.append(f"BGP-001 RESULT: {status}") log.append("-" * 80) return { "router": router_name, "status": status, "results": results, "log": "\n".join(log) } # ================================================== # 5. 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-001-IDENTITY-AS-{timestamp}.txt" ) print("=" * 80) print("SP NETWORKING ACADEMY") print("BGP-001 - ROUTER IDENTITY AND AS VERIFICATION") print("=" * 80) print(f"Execution started: {datetime.now()}") print("Test type: READ ONLY") print("Routers under test: 4") 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"]) # ---------------------------------------------- # FINAL 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" ) summary_lines = [] print("\n" + "=" * 80) print("BGP-001 EXECUTION SUMMARY") print("=" * 80) for item in all_results: router_name = item["router"] status = item["status"] line = f"{router_name}: {status}" summary_lines.append(line) print(line) print(f"\nRouters passed: {passed}/4") print(f"Routers failed: {failed}/4") print(f"Infrastructure errors: {infrastructure_errors}/4") # ---------------------------------------------- # CONSOLIDATED REPORT # ---------------------------------------------- with report_file.open("w", encoding="utf-8") as report: report.write( "SP NETWORKING ACADEMY\n" "BGP-001 - ROUTER IDENTITY AND AS 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") report.write("\n".join(summary_lines)) 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" + "=" * 80 ) report.write("\n".join(all_logs)) report.write( "\n\n" + "=" * 80 + "\nEND OF REPORT\n" + "=" * 80 + "\n" ) print(f"\nConsolidated 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())