| """ |
| Terminal – Cross-OS shell execution with retries and timeouts. |
| |
| This module is a low-level primitive. It: |
| - Connects to remote targets via SSH (Linux) or WinRM (Windows), or |
| falls back to local subprocess execution if no remote target is used. |
| - Executes commands with retries and timeouts. |
| - Returns a normalized result dict: {stdout, stderr, exit_code, status}. |
| |
| IMPORTANT: |
| - Do NOT pass raw LLM text directly into `execute` unless you explicitly |
| intend to (e.g., via an unsafe "terminal_raw" path in the orchestrator). |
| - For local execution, `allow_shell` controls whether `shell=True` is used. |
| """ |
|
|
| import logging |
| import subprocess |
| import time |
| from typing import Any, Dict, Optional |
|
|
| import paramiko |
| import winrm |
|
|
| logger = logging.getLogger(__name__) |
|
|
|
|
| class TerminalAdapter: |
| def __init__( |
| self, |
| target: Dict[str, Any], |
| retries: int = 3, |
| connect_timeout: int = 10, |
| allow_shell: bool = True, |
| ) -> None: |
| """ |
| :param target: dict with keys like: |
| - "ip": str |
| - "os": "linux" | "windows" | "local" | ... |
| - "creds": {"user": "...", "pass": "..."} |
| - "port": int (for SSH) |
| :param retries: how many times to retry connecting. |
| :param connect_timeout: timeout (seconds) for connection attempts. |
| :param allow_shell: if False, local subprocess will *not* use shell=True. |
| (Remote SSH/WinRM still receive the command string.) |
| """ |
| self.target = target or {} |
| self.retries = retries |
| self.connect_timeout = connect_timeout |
| self.allow_shell = allow_shell |
|
|
| |
| self.conn: Optional[Any] = self._connect_with_retry() |
|
|
| |
| |
| |
|
|
| def _connect_with_retry(self) -> Optional[Any]: |
| """ |
| Attempt to establish a connection (SSH/WinRM). Falls back to None for local. |
| """ |
| for attempt in range(self.retries): |
| try: |
| conn = self._connect() |
| if conn is not None: |
| return conn |
| |
| return None |
| except Exception as e: |
| logger.warning( |
| f"TerminalAdapter: connection attempt {attempt + 1} failed: {e}" |
| ) |
| time.sleep(2 * (attempt + 1)) |
|
|
| |
| raise ConnectionError(f"Failed to connect after {self.retries} attempts") |
|
|
| def _connect(self) -> Optional[Any]: |
| """ |
| Set up SSH (Linux) or WinRM (Windows) based on target; return connection object. |
| |
| If the target is explicitly local (os == 'local') or has no IP, return None. |
| """ |
| os_type = self.target.get("os", "linux").lower() |
| ip = self.target.get("ip") |
| creds = self.target.get("creds", {}) |
| port = int(self.target.get("port", 22)) |
|
|
| |
| if not ip or os_type == "local": |
| logger.debug("TerminalAdapter: running in local mode (no remote IP)") |
| return None |
|
|
| if os_type.startswith("linux"): |
| logger.debug(f"TerminalAdapter: setting up SSH client to {ip}:{port}") |
| client = paramiko.SSHClient() |
| client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) |
| client.connect( |
| ip, |
| port=port, |
| username=creds.get("user"), |
| password=creds.get("pass"), |
| timeout=self.connect_timeout, |
| ) |
| return client |
|
|
| if os_type.startswith("win"): |
| logger.debug(f"TerminalAdapter: setting up WinRM session to {ip}") |
| |
| session = winrm.Session( |
| f"https://{ip}:5986", |
| auth=(creds.get("user"), creds.get("pass")), |
| transport="ntlm", |
| ) |
| |
| session.run_cmd("echo test") |
| return session |
|
|
| |
| logger.debug(f"TerminalAdapter: unknown OS '{os_type}', using local mode") |
| return None |
|
|
| |
| |
| |
|
|
| def execute(self, command: str, timeout: int = 60) -> Dict[str, Any]: |
| """ |
| Execute a command on the target (SSH/WinRM/local). |
| |
| :param command: command string to execute remotely or locally. |
| :param timeout: per-command timeout in seconds. |
| :return: dict with keys: |
| - "stdout": str |
| - "stderr": str |
| - "exit_code": int |
| - "status": "success" | "error" |
| """ |
| |
| if isinstance(self.conn, paramiko.SSHClient): |
| return self._execute_ssh(command, timeout) |
|
|
| |
| if isinstance(self.conn, winrm.Session): |
| return self._execute_winrm(command, timeout) |
|
|
| |
| return self._execute_local(command, timeout) |
|
|
| def _execute_ssh(self, command: str, timeout: int) -> Dict[str, Any]: |
| logger.debug(f"TerminalAdapter[SSH] executing: {command}") |
| try: |
| stdin, stdout, stderr = self.conn.exec_command( |
| command, |
| timeout=timeout, |
| ) |
| exit_code = stdout.channel.recv_exit_status() |
| out = stdout.read().decode(errors="ignore") |
| err = stderr.read().decode(errors="ignore") |
| status = "success" if exit_code == 0 else "error" |
| return { |
| "stdout": out, |
| "stderr": err, |
| "exit_code": exit_code, |
| "status": status, |
| } |
| except Exception as e: |
| logger.error(f"TerminalAdapter[SSH] execution error: {e}") |
| return { |
| "stdout": "", |
| "stderr": str(e), |
| "exit_code": -1, |
| "status": "error", |
| } |
|
|
| def _execute_winrm(self, command: str, timeout: int) -> Dict[str, Any]: |
| logger.debug(f"TerminalAdapter[WinRM] executing: {command}") |
| try: |
| result = self.conn.run_cmd( |
| command, |
| timeout_sec=timeout, |
| ) |
| out = result.std_out.decode("utf-8", errors="ignore") |
| err = result.std_err.decode("utf-8", errors="ignore") |
| exit_code = result.status_code |
| status = "success" if exit_code == 0 else "error" |
| return { |
| "stdout": out, |
| "stderr": err, |
| "exit_code": exit_code, |
| "status": status, |
| } |
| except Exception as e: |
| logger.error(f"TerminalAdapter[WinRM] execution error: {e}") |
| return { |
| "stdout": "", |
| "stderr": str(e), |
| "exit_code": -1, |
| "status": "error", |
| } |
|
|
| def _execute_local(self, command: str, timeout: int) -> Dict[str, Any]: |
| """ |
| Execute a command locally. By default uses shell=True for backward |
| compatibility and flexibility, but this is controlled by allow_shell. |
| |
| Note: This method does NOT know anything about the LLM. The orchestrator |
| should decide whether it is acceptable to pass LLM-originated strings |
| into this function. |
| """ |
| logger.debug( |
| f"TerminalAdapter[local] executing: {command} (shell={self.allow_shell})" |
| ) |
| try: |
| if self.allow_shell: |
| proc = subprocess.run( |
| command, |
| shell=True, |
| capture_output=True, |
| text=True, |
| timeout=timeout, |
| ) |
| else: |
| |
| |
| |
| proc = subprocess.run( |
| command.split(), |
| shell=False, |
| capture_output=True, |
| text=True, |
| timeout=timeout, |
| ) |
|
|
| out = proc.stdout |
| err = proc.stderr |
| exit_code = proc.returncode |
| status = "success" if exit_code == 0 else "error" |
| return { |
| "stdout": out, |
| "stderr": err, |
| "exit_code": exit_code, |
| "status": status, |
| } |
| except subprocess.TimeoutExpired: |
| logger.warning("TerminalAdapter[local] command timed out") |
| return { |
| "stdout": "", |
| "stderr": "Timeout", |
| "exit_code": -1, |
| "status": "error", |
| } |
| except Exception as e: |
| logger.error(f"TerminalAdapter[local] execution error: {e}") |
| return { |
| "stdout": "", |
| "stderr": str(e), |
| "exit_code": -1, |
| "status": "error", |
| } |
|
|