Coverage for src/romfarmer/farmhand/ssh.py: 0%
174 statements
« prev ^ index » next coverage.py v7.15.4, created at 2026-09-01 23:08 -0700
« prev ^ index » next coverage.py v7.15.4, created at 2026-09-01 23:08 -0700
1"""SSH client wrapper using Paramiko.
3Provides a clean interface for connecting to remote targets,
4executing commands, and transferring files over SFTP.
5"""
7from __future__ import annotations
9import logging
10import stat
11from collections.abc import Callable
12from pathlib import Path, PurePosixPath
13from typing import Any
15logger = logging.getLogger(__name__)
17try:
18 import paramiko
19 from paramiko import SFTPClient
20 from paramiko import SSHClient as _ParamikoSSHClient
22 PARAMIKO_AVAILABLE = True
23except ImportError:
24 PARAMIKO_AVAILABLE = False
26# Type alias for progress callbacks: (bytes_transferred, total_bytes)
27ProgressCallback = Callable[[int, int], None]
30class SSHError(Exception):
31 """SSH operation failed."""
34class SSHClient:
35 """Paramiko-based SSH client for Farm-Hand target operations.
37 Manages a persistent SSH connection to a remote target, providing
38 command execution and SFTP file transfer with progress tracking.
40 Usage:
41 client = SSHClient("192.0.2.10", user="root", password="linux")
42 client.connect()
43 output = client.run("df -h")
44 client.upload("/local/file.chd", "/userdata/roms/psx/file.chd")
45 client.close()
47 Context manager:
48 with SSHClient("192.0.2.10", user="root", password="linux") as ssh:
49 output = ssh.run("uname -a")
50 """
52 def __init__(
53 self,
54 host: str,
55 port: int = 22,
56 user: str = "root",
57 password: str | None = None,
58 key_file: str | None = None,
59 connect_timeout: float = 10.0,
60 ) -> None:
61 if not PARAMIKO_AVAILABLE:
62 raise ImportError(
63 "paramiko is required for Farm-Hand SSH operations. "
64 "Install with: pip install 'romfarmer[farmhand]'"
65 )
67 self.host = host
68 self.port = port
69 self.user = user
70 self.password = password
71 self.key_file = key_file
72 self.connect_timeout = connect_timeout
74 self._client: _ParamikoSSHClient | None = None
75 self._sftp: SFTPClient | None = None
77 # -- lifecycle ----------------------------------------------------------
79 def connect(self) -> None:
80 """Establish SSH connection to the target."""
81 if self._client is not None:
82 return # already connected
84 self._client = _ParamikoSSHClient()
85 self._client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
87 kwargs: dict[str, Any] = {
88 "hostname": self.host,
89 "port": self.port,
90 "username": self.user,
91 "timeout": self.connect_timeout,
92 "allow_agent": False,
93 "look_for_keys": False,
94 }
96 if self.key_file:
97 kwargs["key_filename"] = self.key_file
98 elif self.password:
99 kwargs["password"] = self.password
100 else:
101 # Try agent / default keys as last resort
102 kwargs["allow_agent"] = True
103 kwargs["look_for_keys"] = True
105 try:
106 self._client.connect(**kwargs)
107 logger.info("SSH connected to %s@%s:%d", self.user, self.host, self.port)
108 except Exception as exc:
109 self._client = None
110 raise SSHError(f"SSH connection to {self.host}:{self.port} failed: {exc}") from exc
112 def close(self) -> None:
113 """Close the SSH connection and SFTP channel."""
114 if self._sftp:
115 try:
116 self._sftp.close()
117 except Exception:
118 pass
119 self._sftp = None
120 if self._client:
121 try:
122 self._client.close()
123 except Exception:
124 pass
125 self._client = None
126 logger.info("SSH disconnected from %s", self.host)
128 @property
129 def is_connected(self) -> bool:
130 """Check if SSH connection is alive."""
131 if self._client is None:
132 return False
133 transport = self._client.get_transport()
134 return transport is not None and transport.is_active()
136 def __enter__(self) -> SSHClient:
137 self.connect()
138 return self
140 def __exit__(self, *args: Any) -> None:
141 self.close()
143 # -- command execution --------------------------------------------------
145 def run(self, command: str, timeout: float = 30.0) -> str:
146 """Execute a command on the remote target and return stdout.
148 Args:
149 command: Shell command to execute.
150 timeout: Maximum seconds to wait for completion.
152 Returns:
153 stdout output as a string.
155 Raises:
156 SSHError: If the command fails (non-zero exit) or connection is down.
157 """
158 if not self.is_connected:
159 raise SSHError("Not connected — call connect() first")
161 assert self._client is not None
162 try:
163 stdin, stdout, stderr = self._client.exec_command(command, timeout=timeout)
164 exit_code = stdout.channel.recv_exit_status()
165 out = stdout.read().decode("utf-8", errors="replace")
166 err = stderr.read().decode("utf-8", errors="replace")
168 if exit_code != 0:
169 logger.warning("Command '%s' exited %d: %s", command, exit_code, err.strip())
170 # Still return output — many Batocera commands have
171 # non-zero exits for benign reasons.
173 return out
174 except Exception as exc:
175 raise SSHError(f"Command execution failed: {exc}") from exc
177 def run_checked(self, command: str, timeout: float = 30.0) -> str:
178 """Like run(), but raises SSHError on non-zero exit code."""
179 if not self.is_connected:
180 raise SSHError("Not connected — call connect() first")
182 assert self._client is not None
183 stdin, stdout, stderr = self._client.exec_command(command, timeout=timeout)
184 exit_code = stdout.channel.recv_exit_status()
185 out = stdout.read().decode("utf-8", errors="replace")
186 err = stderr.read().decode("utf-8", errors="replace")
188 if exit_code != 0:
189 raise SSHError(f"Command '{command}' failed (exit {exit_code}): {err.strip()}")
190 return out
192 # -- SFTP operations ----------------------------------------------------
194 def _get_sftp(self) -> SFTPClient:
195 """Get or create the SFTP channel."""
196 if not self.is_connected:
197 raise SSHError("Not connected — call connect() first")
199 if self._sftp is None:
200 assert self._client is not None
201 self._sftp = self._client.open_sftp()
202 return self._sftp
204 def list_dir(self, remote_path: str) -> list[str]:
205 """List directory contents on the remote target.
207 Returns:
208 List of entry names. Directories end with '/'.
209 """
210 sftp = self._get_sftp()
211 results: list[str] = []
212 for entry in sftp.listdir_attr(remote_path):
213 name = entry.filename
214 if stat.S_ISDIR(entry.st_mode or 0):
215 name += "/"
216 results.append(name)
217 return sorted(results)
219 def stat_remote(self, remote_path: str) -> paramiko.SFTPAttributes | None:
220 """Stat a remote file. Returns None if not found."""
221 sftp = self._get_sftp()
222 try:
223 return sftp.stat(remote_path)
224 except FileNotFoundError:
225 return None
227 def mkdir_p(self, remote_path: str) -> None:
228 """Create remote directory, including parents (like mkdir -p)."""
229 sftp = self._get_sftp()
230 parts = PurePosixPath(remote_path).parts
231 current = ""
232 for part in parts:
233 current = current + "/" + part if current else "/" + part
234 if current == "/":
235 continue
236 try:
237 sftp.stat(current)
238 except FileNotFoundError:
239 sftp.mkdir(current)
240 logger.debug("Created remote dir: %s", current)
242 def upload(
243 self,
244 local_path: str | Path,
245 remote_path: str,
246 progress_callback: ProgressCallback | None = None,
247 ) -> int:
248 """Upload a file to the remote target via SFTP.
250 Args:
251 local_path: Local file path.
252 remote_path: Remote destination path.
253 progress_callback: Called with (bytes_transferred, total_bytes).
255 Returns:
256 Bytes transferred.
257 """
258 sftp = self._get_sftp()
259 local_path = Path(local_path)
261 if not local_path.exists():
262 raise SSHError(f"Local file not found: {local_path}")
264 file_size = local_path.stat().st_size
266 # Ensure remote directory exists
267 remote_dir = str(PurePosixPath(remote_path).parent)
268 self.mkdir_p(remote_dir)
270 def _progress(transferred: int, total: int) -> None:
271 if progress_callback:
272 progress_callback(transferred, total)
274 sftp.put(str(local_path), remote_path, callback=_progress)
275 logger.debug("Uploaded %s -> %s (%d bytes)", local_path, remote_path, file_size)
276 return file_size
278 def download(
279 self,
280 remote_path: str,
281 local_path: str | Path,
282 progress_callback: ProgressCallback | None = None,
283 ) -> int:
284 """Download a file from the remote target via SFTP.
286 Returns:
287 Bytes transferred.
288 """
289 sftp = self._get_sftp()
290 local_path = Path(local_path)
291 local_path.parent.mkdir(parents=True, exist_ok=True)
293 remote_stat = sftp.stat(remote_path)
294 file_size = remote_stat.st_size or 0
296 def _progress(transferred: int, total: int) -> None:
297 if progress_callback:
298 progress_callback(transferred, total)
300 sftp.get(remote_path, str(local_path), callback=_progress)
301 logger.debug("Downloaded %s -> %s (%d bytes)", remote_path, local_path, file_size)
302 return file_size
304 def remove(self, remote_path: str) -> None:
305 """Remove a remote file."""
306 sftp = self._get_sftp()
307 sftp.remove(remote_path)
309 def disk_usage(self) -> str:
310 """Get disk usage (df -h) from target."""
311 return self.run("df -h")
313 def file_count(self, remote_path: str) -> int:
314 """Count files recursively under a remote path."""
315 output = self.run(f"find {remote_path} -type f 2>/dev/null | wc -l", timeout=60)
316 try:
317 return int(output.strip())
318 except ValueError:
319 return 0
321 def dir_size_bytes(self, remote_path: str) -> int:
322 """Get total size of a remote directory in bytes."""
323 output = self.run(f"du -sb {remote_path} 2>/dev/null | cut -f1", timeout=120)
324 try:
325 return int(output.strip())
326 except ValueError:
327 return 0