Initializes the global Metasploit RPC client instance. Raises exceptions on failure.
()
| 64 | _msf_client_instance: Optional[MsfRpcClient] = None |
| 65 | |
| 66 | def initialize_msf_client() -> MsfRpcClient: |
| 67 | """ |
| 68 | Initializes the global Metasploit RPC client instance. |
| 69 | Raises exceptions on failure. |
| 70 | """ |
| 71 | global _msf_client_instance |
| 72 | if _msf_client_instance is not None: |
| 73 | return _msf_client_instance |
| 74 | |
| 75 | logger.info("Attempting to initialize Metasploit RPC client...") |
| 76 | |
| 77 | try: |
| 78 | msf_port = int(MSF_PORT_STR) |
| 79 | msf_ssl = MSF_SSL_STR.lower() == 'true' |
| 80 | except ValueError as e: |
| 81 | logger.error(f"Invalid MSF connection parameters (PORT: {MSF_PORT_STR}, SSL: {MSF_SSL_STR}). Error: {e}") |
| 82 | raise ValueError("Invalid MSF connection parameters") from e |
| 83 | |
| 84 | try: |
| 85 | logger.debug(f"Attempting to create MsfRpcClient connection to {MSF_SERVER}:{msf_port} (SSL: {msf_ssl})...") |
| 86 | client = MsfRpcClient( |
| 87 | password=MSF_PASSWORD, |
| 88 | server=MSF_SERVER, |
| 89 | port=msf_port, |
| 90 | ssl=msf_ssl |
| 91 | ) |
| 92 | # Test connection during initialization |
| 93 | logger.debug("Testing connection with core.version call...") |
| 94 | version_info = client.core.version |
| 95 | msf_version = version_info.get('version', 'unknown') if isinstance(version_info, dict) else 'unknown' |
| 96 | logger.info(f"Successfully connected to Metasploit RPC at {MSF_SERVER}:{msf_port} (SSL: {msf_ssl}), version: {msf_version}") |
| 97 | _msf_client_instance = client |
| 98 | return _msf_client_instance |
| 99 | except MsfRpcError as e: |
| 100 | logger.error(f"Failed to connect or authenticate to Metasploit RPC ({MSF_SERVER}:{msf_port}, SSL: {msf_ssl}): {e}") |
| 101 | raise ConnectionError(f"Failed to connect/authenticate to Metasploit RPC: {e}") from e |
| 102 | except Exception as e: |
| 103 | logger.error(f"An unexpected error occurred during MSF client initialization: {e}", exc_info=True) |
| 104 | raise RuntimeError(f"Unexpected error initializing MSF client: {e}") from e |
| 105 | |
| 106 | def get_msf_client() -> MsfRpcClient: |
| 107 | """Gets the initialized MSF client instance, raising an error if not ready.""" |
no outgoing calls