fix(ssh): raise when a node command cannot run, drop the execute call
driver / standard (pull_request) Successful in 18s
driver / lint (pull_request) Successful in 16s
driver / types (pull_request) Successful in 1m10s
driver / test (3.12) (pull_request) Successful in 1m9s
driver / test (3.13) (pull_request) Successful in 1m4s
driver / lowest (pull_request) Successful in 35s
driver / build (pull_request) Successful in 40s
driver / security (pull_request) Successful in 1m15s
CI / driver (pull_request) Successful in 2m53s
driver / publish (pull_request) Skipped

_exec_ssh_command returned "" on any failure (no SSH credential, a
refused login or host key, an unreachable node, a timeout), so a
getter that could not look read like one that found nothing; on
API-token-only nodes get_snmp_config answered None and the SSH-backed
getters empty lists on every poll. It now raises ConnectionException
with the cause (SshHostKeyMismatch as it is), and refuses before
connecting when there is neither a password nor a usable key.

It returned stderr when stdout was empty; output is stdout now. It
first posted every command to /nodes/{node}/execute, which runs a
batch of API calls rather than a shell; that dead round trip is gone.

The key types, the key before the password, the host-key check and the
single connect path were done in f491f9f and 6bb3035. The shared
transport is NAPALM/napalm-device-types#35.

Closes #17
This commit is contained in:
Christian Manivong committed 2026-11-02 08:52:32 +01:00
1 parent bfba804ec2
commit daf1b519eb
13 files changed
+261 -108

No files matched your search

+3 -3
View File
@@ -114,12 +114,12 @@ class ProxmoxConfigMixin:
.. note::
Full programmatic apply requires the Proxmox API to accept raw
interface configs. This implementation uses ``pvesh`` via exec
which requires the node exec endpoint to be available.
interface configs. This implementation uses ``pvesh`` over the
node's SSH session.
"""
if not self._candidate_config:
return
# Write via exec endpoint
# Write over the node's SSH session
escaped = self._candidate_config.replace("'", "'\\''")
self._exec_ssh_command(
f"printf '%s' '{escaped}' > /etc/network/interfaces && "
+39 -33
View File
@@ -48,7 +48,7 @@ from napalm_device_types import (
SystemdServicesMixin,
SystemIdentityMixin,
)
from napalm_device_types.ssh_host_keys import HostKeyCheck, SshHostKeyMismatch
from napalm_device_types.ssh_host_keys import HostKeyCheck
try:
from proxmoxer import ProxmoxAPI
@@ -299,48 +299,40 @@ class ProxmoxDriver(
return []
def _exec_ssh_command(self, command: str) -> str:
"""Execute a shell command on the Proxmox node and return output.
"""Run *command* in the node's shell over SSH and return what it printed.
Tries the Proxmox API exec endpoint first. If that fails,
falls back to a direct paramiko SSH connection.
Stdout only: stderr is not output (a command that wants it says
``2>&1``). The exit status is not checked; a caller that needs it asks
for it (``_rc``). The node has no API endpoint that runs a shell command
(``/nodes/{node}/execute`` runs a batch of API calls), so this is the
one way, the same session ``_run_node_command`` uses (see
NAPALM/napalm-device-types#35 for the shared transport).
:raises ConnectionException: when the command could not run: no SSH
credential, a refused login or host key (``SshHostKeyMismatch``),
an unreachable node, a timeout.
"""
import base64 as _b64
# Try API exec endpoint
try:
encoded = _b64.b64encode(command.encode()).decode()
result = self._node_api().execute.post("command", f"echo {encoded} | base64 -d | sh")
# On PVE 8.x the exec endpoint returns a dict with 'data' key
if isinstance(result, dict):
raw = result.get("data", result.get("output", ""))
else:
raw = result
if raw:
return str(raw).strip()
except Exception as exc:
logger.debug("API exec failed, falling back to SSH: %s", exc)
# Fallback: direct paramiko SSH
try:
_, stdout, stderr = self._node_ssh().exec_command(command, timeout=self.timeout)
err = stderr.read().decode().strip()
out = stdout.read().decode().strip()
return out or err
except ImportError:
logger.warning("paramiko not installed — cannot exec SSH commands")
except SshHostKeyMismatch as exc:
# Refused before any login, and already reported to the caller's store.
logger.warning("%s", exc)
except Exception as exc:
logger.debug("SSH exec command failed: %s", exc)
return ""
out = stdout.read().decode(errors="replace")
err = stderr.read().decode(errors="replace").strip()
except ConnectionException:
raise
except _ssh_errors() as exc:
raise ConnectionException(
f"Cannot run a command on {self.hostname} over SSH: {exc}"
) from exc
if err:
logger.debug("%s: stderr of a node command: %s", self.hostname, err[-300:])
return out.strip()
def _node_ssh(self) -> Any: # paramiko.SSHClient; paramiko is imported lazily
"""The SSH session to the node on port 22, opened once.
Its host key is the one the caller expects for port 22, or on first use
whichever the node presents; either way it is reported (netork#1167).
:raises ConnectionException: without a password or a usable key.
"""
import paramiko
@@ -356,6 +348,12 @@ class ProxmoxDriver(
pkey = _load_private_key(self._ssh_key) if self._ssh_key else None
if pkey is not None:
connect_kwargs["pkey"] = pkey
if not password and pkey is None:
# An API-token-only node: nothing to log in with, so no connection.
raise ConnectionException(
f"no SSH credential for {self.hostname}: set ssh_password or "
"ssh_private_key_str"
)
client = paramiko.SSHClient()
try:
HostKeyCheck(self.optional_args, self.hostname, 22).connect(
@@ -528,3 +526,11 @@ def _load_private_key(text: str) -> Any: # paramiko.PKey; paramiko is imported
continue
logger.warning("The SSH private key could not be read; logging in with the password")
return None
def _ssh_errors() -> tuple[type[Exception], ...]:
"""What a command that could not run raises: the socket's errors, timeouts
included, and paramiko's (a refused login, a closed session)."""
import paramiko
return (OSError, paramiko.SSHException)
+3 -3
View File
@@ -160,9 +160,9 @@ class ProxmoxInterfaceMixin:
def get_arp_table(self, vrf: str = "") -> list[_JsonDict]:
"""Return ARP table.
Proxmox does not expose ARP via the REST API directly. We attempt
to read it via the node's ``/proc/net/arp`` through the Proxmox
exec endpoint. If that is unavailable, an empty list is returned.
Proxmox does not expose ARP via the REST API, so the node's
``/proc/net/arp`` is read over SSH; a node that cannot be reached
there raises.
"""
raw = self._exec_ssh_command("cat /proc/net/arp")
if not raw:
+2 -2
View File
@@ -58,7 +58,7 @@ class ProxmoxRoutingMixin:
raw = self._exec_ssh_command(f"{cmd} 2>&1 || true")
if not raw:
return {"error": "Ping command not available via exec endpoint"}
return {"error": "ping printed nothing on the node"}
# Detect common failure strings before parsing statistics
_error_patterns = (
@@ -126,7 +126,7 @@ class ProxmoxRoutingMixin:
raw = self._exec_ssh_command(" ".join(cmd_parts) + " 2>&1 || true")
if not raw:
return {"error": "traceroute not available via exec endpoint"}
return {"error": "traceroute printed nothing on the node"}
hops: _JsonDict = {}
for line in raw.splitlines():
+2 -1
View File
@@ -504,7 +504,8 @@ class ProxmoxSystemMixin:
def get_snmp_config(self):
"""Return SNMP agent config if snmpd is installed and running on the node.
Uses _exec_ssh_command (Proxmox API exec or SSH) to inspect the node.
Uses _exec_ssh_command (the node's SSH session) to inspect the node;
raises when the node cannot be reached there.
Returns a SNMPConfigDict or None.
"""
try:
+4 -4
View File
@@ -129,10 +129,10 @@ class ProxmoxVMProvisionMixin:
"""
Execute a shell command on the Proxmox node via SSH, raising on failure.
Unlike ``_exec_ssh_command`` (best-effort, fixed timeout, swallows
errors), this is for critical provisioning steps — image download,
disk import — where a non-zero exit or a caller-specific timeout must
surface as a hard failure rather than an empty string.
Unlike ``_exec_ssh_command`` (fixed timeout, exit status not checked),
this is for critical provisioning steps — image download, disk import —
where a non-zero exit or a caller-specific timeout must surface as a
hard failure.
"""
_, stdout, stderr = self._node_ssh().exec_command(command, timeout=timeout)
exit_status = stdout.channel.recv_exit_status()