From 874e25a1ce9bbcbb6b29ff8c2a8eedb6b62a36df Mon Sep 17 00:00:00 2001 From: Christian Manivong Date: Sun, 1 Nov 2026 21:44:52 +0100 Subject: [PATCH 1/5] fix(snmp): open the REST side session's SSH on port 22 configure_snmp_agent over the REST API opened its temporary SSH session on optional_args["port"], which names the REST API's port when REST is the transport. It now uses port 22, as the running-config fallback already did. The second finding of the issue, the unverified REST certificate, needs a decision and stays open. Refs #17 --- CHANGELOG.md | 5 +++++ napalm_procurve/procurve.py | 10 +++++----- tests/unit/test_ssh_host_key.py | 15 ++++++++++++++- 3 files changed, 24 insertions(+), 6 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index d3265a2..ea54f2d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -14,6 +14,11 @@ All notable changes to this driver. The format follows - The floor on urllib3 is 1.26.5: older releases bundle a `six` that Python 3.12 cannot import. +### Fixed +- `configure_snmp_agent` over the REST API opens its temporary SSH session on port 22. + It used `optional_args["port"]`, which names the REST API's port when REST is the + transport, so the SNMP setup failed on switches managed over REST. + ## [0.6.0] - 2026-10-23 The first release on PyPI. diff --git a/napalm_procurve/procurve.py b/napalm_procurve/procurve.py index fdb9404..92f3e8d 100644 --- a/napalm_procurve/procurve.py +++ b/napalm_procurve/procurve.py @@ -79,6 +79,7 @@ _SSH_DISABLED_LEGACY = { } +_SSH_PORT_BESIDE_API = 22 # SSH beside the REST API: ``port`` then is the API's (#17) #: What may stand in a quoted CLI value: no whitespace, quote or #. _CLI_WORD = re.compile(r'^[^\s"#]+$') @@ -663,11 +664,10 @@ class ProcurveDriver(ConfigLifecycleMixin, SwitchDriver): HP ProCurve switches do not support exec_channel SSH; they require an interactive shell (invoke_shell), which netmiko's hp_procurve - device type handles correctly. Port 22 is used explicitly because - self.port is the REST API port (443) in API transport mode. + device type handles correctly. Port 22: ``port`` is the REST API's. """ try: - conn = self._ssh_connect(port=22) # always SSH — self.port is the REST API port + conn = self._ssh_connect(port=_SSH_PORT_BESIDE_API) try: return conn.send_command("show running-config") finally: @@ -1254,7 +1254,7 @@ class ProcurveDriver(ConfigLifecycleMixin, SwitchDriver): """The agent is built in; configure community, contact and location, then save. The REST API has no writable SNMP endpoint, so over REST a temporary SSH - session runs the config-mode CLI. + session on port 22 runs the config-mode CLI. """ steps = [ ("install", lambda: {"ok": True, "output": "the SNMP agent is built in"}), @@ -1269,7 +1269,7 @@ class ProcurveDriver(ConfigLifecycleMixin, SwitchDriver): ssh_error = "" for legacy in (False, True): try: - self._device = self._ssh_connect(legacy) + self._device = self._ssh_connect(legacy, port=_SSH_PORT_BESIDE_API) self._transport = "ssh_legacy" if legacy else "ssh" break except SshHostKeyMismatch as exc: # the same host either way diff --git a/tests/unit/test_ssh_host_key.py b/tests/unit/test_ssh_host_key.py index 9585b18..eb193da 100644 --- a/tests/unit/test_ssh_host_key.py +++ b/tests/unit/test_ssh_host_key.py @@ -104,7 +104,7 @@ def test_the_config_fallback_checks_the_key_of_port_22(): def test_the_snmp_fix_over_rest_stops_at_a_changed_key(): seen: list = [] - driver = _driver(seen, {"443": SshHostKey.of(OTHER_KEY).as_dict()}, port=443) + driver = _driver(seen, {"22": SshHostKey.of(OTHER_KEY).as_dict()}, port=443) driver._transport = "api" driver._api = MagicMock() with patch(HANDLER, side_effect=_refuse) as handler: @@ -112,3 +112,16 @@ def test_the_snmp_fix_over_rest_stops_at_a_changed_key(): assert result["success"] is False assert handler.call_count == 1 assert "host key" in str(result) + + +def test_the_snmp_fix_over_rest_opens_ssh_on_port_22_not_the_api_port(): + """``port`` is the REST API's port when REST is the transport (#17).""" + seen: list = [] + driver = _driver(seen, {"22": SshHostKey.of(SERVER_KEY).as_dict()}, port=443) + driver._transport = "api" + driver._api = MagicMock() + with patch(HANDLER, return_value=_device()) as handler: + driver.configure_snmp_agent({"community": "c0mm", "allowed_sources": []}) + assert handler.call_args.kwargs["port"] == 22 + assert handler.call_args.kwargs["ssh_strict"] is True + assert (seen[0]["port"], seen[0]["accepted"]) == (22, True) From ee49948b2bfa40070ffbeed978b4154f0e00b7ae Mon Sep 17 00:00:00 2001 From: Christian Manivong Date: Sun, 1 Nov 2026 21:48:56 +0100 Subject: [PATCH 2/5] fix(connect): name a full switch and a web page, not a bad password A switch whose Telnet sessions were all taken, and a REST API answering the login with the web UI's HTML page, were both reported as an authentication failure, which sent the operator after the password. The Telnet login now keeps the switch's greeting in an in-memory session log and reports a full switch as a connection error; an HTML answer to the REST login says so. An SSH attempt records netmiko's underlying error instead of "timed out" when it was not a timeout. Session log objects need netmiko 4.3.0, which becomes the floor. Closes #13 --- CHANGELOG.md | 9 ++ napalm_procurve/api_client.py | 6 ++ napalm_procurve/connect_reasons.py | 56 +++++++++++ napalm_procurve/procurve.py | 19 ++-- pyproject.toml | 2 +- tests/quality_baseline.json | 2 +- tests/unit/test_connect_reasons.py | 151 +++++++++++++++++++++++++++++ 7 files changed, 233 insertions(+), 12 deletions(-) create mode 100644 napalm_procurve/connect_reasons.py create mode 100644 tests/unit/test_connect_reasons.py diff --git a/CHANGELOG.md b/CHANGELOG.md index ea54f2d..6886adf 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -13,11 +13,20 @@ All notable changes to this driver. The format follows 3.12 venv no longer has. - The floor on urllib3 is 1.26.5: older releases bundle a `six` that Python 3.12 cannot import. +- The floor on netmiko is 4.3.0: the Telnet login reads the switch's greeting through + a session log object, which older releases do not accept. ### Fixed - `configure_snmp_agent` over the REST API opens its temporary SSH session on port 22. It used `optional_args["port"]`, which names the REST API's port when REST is the transport, so the SNMP setup failed on switches managed over REST. +- A switch whose Telnet sessions are all taken is reported as such ("the switch has no + free session"), as a connection error. It was reported as an authentication failure, + which pointed at the password. +- A REST API that answers the login with an HTML page is reported as "answered with a + web page instead of JSON", not as a failed login. +- An SSH attempt that failed for another reason than a timeout, such as no common key + exchange algorithm, names that reason instead of "timed out". ## [0.6.0] - 2026-10-23 diff --git a/napalm_procurve/api_client.py b/napalm_procurve/api_client.py index 6a840b7..f64a0de 100644 --- a/napalm_procurve/api_client.py +++ b/napalm_procurve/api_client.py @@ -124,6 +124,12 @@ class ProcurveApiClient: json={"userName": self.username, "password": self.password}, timeout=self.timeout, ) + if "html" in resp.headers.get("Content-Type", "").lower(): + # The web UI's "session timed out" page, for any user (#13): not a login result. + raise ConnectionException( + f"REST API on {self.hostname} answered with a web page instead of JSON " + f"(HTTP {resp.status_code})" + ) if resp.status_code != 201: raise ConnectAuthError( f"REST API login failed (HTTP {resp.status_code}) for {self.hostname}" diff --git a/napalm_procurve/connect_reasons.py b/napalm_procurve/connect_reasons.py new file mode 100644 index 0000000..d6cddf4 --- /dev/null +++ b/napalm_procurve/connect_reasons.py @@ -0,0 +1,56 @@ +# Licensed under the Apache License, Version 2.0 + +"""Why a transport failed, in the switch's terms rather than netmiko's. + +netmiko reports a Telnet greeting that refuses every login as a failed login, +and every paramiko error during the SSH handshake as a timeout. These helpers +recover what actually happened, so a busy switch does not read as a wrong +password and a key-exchange mismatch not as an unreachable host. +""" + +from __future__ import annotations + +import re + +from netmiko.exceptions import NetmikoTimeoutException +from netmiko.session_log import SessionLog + +#: What the switch prints instead of a login prompt when every Telnet session is taken. +_NO_FREE_SESSION = re.compile(r"maximum number of telnet sessions", re.I) + +#: Only the greeting matters; the session that follows is not kept in memory. +_GREETING_CHARS = 4096 + +NO_FREE_TELNET_SESSION = "the switch has no free session (maximum number of telnet sessions active)" + + +class TelnetTranscript(SessionLog): + """The start of what the switch sent, in memory; netmiko's writes are not recorded.""" + + def __init__(self) -> None: + super().__init__(record_writes=False) + self.text = "" + + def write(self, data: str) -> None: + """Keep the start of what netmiko read from the channel.""" + if len(self.text) < _GREETING_CHARS: + self.text += data + + @property + def no_free_session(self) -> bool: + """Whether the switch refused the session before any login.""" + return bool(_NO_FREE_SESSION.search(self.text)) + + +def failure_reason(exc: Exception) -> str: + """The reason to record for a failed SSH attempt. + + netmiko raises :class:`NetmikoTimeoutException` for a socket error and for any + paramiko error alike; the original one is its context. + """ + if not isinstance(exc, NetmikoTimeoutException): + return str(exc) + cause = exc.__cause__ or exc.__context__ + if cause is None or isinstance(cause, TimeoutError): + return "timed out" + return str(cause) or type(cause).__name__ diff --git a/napalm_procurve/procurve.py b/napalm_procurve/procurve.py index 92f3e8d..57d439f 100644 --- a/napalm_procurve/procurve.py +++ b/napalm_procurve/procurve.py @@ -42,13 +42,11 @@ from napalm_device_types.ssh_host_keys import ( SshHostKeyMismatch, ) from netmiko import ConnectHandler -from netmiko.exceptions import ( - NetmikoAuthenticationException, - NetmikoTimeoutException, -) +from netmiko.exceptions import NetmikoAuthenticationException from napalm_procurve import parsers from napalm_procurve.api_client import ProcurveApiClient +from napalm_procurve.connect_reasons import NO_FREE_TELNET_SESSION, TelnetTranscript, failure_reason logger = logging.getLogger("napalm_procurve") @@ -363,18 +361,15 @@ class ProcurveDriver(ConfigLifecycleMixin, SwitchDriver): raise except NetmikoAuthenticationException as exc: raise self._auth_failure(transport, exc) from exc - except NetmikoTimeoutException: - logger.debug("%s timeout for %s", label, self.hostname) - self._attempts.append(f"{transport}: timed out") - return False except Exception as exc: logger.debug("%s failed for %s: %s", label, self.hostname, exc) - self._attempts.append(f"{transport}: {exc}") + self._attempts.append(f"{transport}: {failure_reason(exc)}") return False def _try_telnet(self) -> bool: """Probe and connect via Telnet. Returns True on success.""" logger.debug("Trying Telnet for %s", self.hostname) + transcript = TelnetTranscript() # a full switch refuses before the login (#13) try: conn = ConnectHandler( device_type=self.NETMIKO_DEVICE_TYPE_TELNET, @@ -384,13 +379,17 @@ class ProcurveDriver(ConfigLifecycleMixin, SwitchDriver): secret=self._secret, port=self.telnet_port, timeout=self.timeout, + session_log=transcript, ) self._device = conn self._transport = "telnet" logger.info("Connected to %s via Telnet", self.hostname) return True except NetmikoAuthenticationException as exc: - raise self._auth_failure("telnet", exc) from exc + if not transcript.no_free_session: + raise self._auth_failure("telnet", exc) from exc + self._attempts.append(f"telnet: {NO_FREE_TELNET_SESSION}") + return False except Exception as exc: logger.debug("Telnet failed for %s: %s", self.hostname, exc) self._attempts.append(f"telnet: {exc}") diff --git a/pyproject.toml b/pyproject.toml index e600527..7a95fe3 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -23,7 +23,7 @@ classifiers = [ dependencies = [ "napalm>=5.1", # older releases import pkg_resources, which a 3.12 venv lacks "napalm-device-types>=4.21.1", - "netmiko>=4.0.0", + "netmiko>=4.3.0", # takes a SessionLog object as session_log "paramiko>=5.0.0", # CVE-2026-44405 "netaddr>=0.7.10", "requests>=2.25.0", diff --git a/tests/quality_baseline.json b/tests/quality_baseline.json index e824903..bc105ba 100644 --- a/tests/quality_baseline.json +++ b/tests/quality_baseline.json @@ -27,7 +27,7 @@ "napalm_procurve.procurve" ], "python_file_lines": { - "napalm_procurve/procurve.py": 1397 + "napalm_procurve/procurve.py": 1396 }, "untyped_public": [ "napalm_procurve/procurve.py::ProcurveDriver.get_snmp_config" diff --git a/tests/unit/test_connect_reasons.py b/tests/unit/test_connect_reasons.py new file mode 100644 index 0000000..dc6c69f --- /dev/null +++ b/tests/unit/test_connect_reasons.py @@ -0,0 +1,151 @@ +"""A failed connection names what the switch actually said (#13). + +A switch whose Telnet sessions are all taken, a REST API that answers with the +web UI's HTML page, and an SSH key exchange that found no common algorithm were +all reported as a wrong password or a timeout, which sends the operator after +the credentials instead of the session table. +""" + +from __future__ import annotations + +from unittest.mock import MagicMock, patch + +import paramiko +import pytest +from napalm.base.exceptions import ConnectAuthError, ConnectionException +from netmiko.exceptions import NetmikoAuthenticationException, NetmikoTimeoutException + +from napalm_procurve.api_client import ProcurveApiClient +from napalm_procurve.procurve import ProcurveDriver + +HANDLER = "napalm_procurve.procurve.ConnectHandler" +PROBE = "napalm_procurve.procurve.ProcurveApiClient.probe" + +# What a ProCurve 2520G prints instead of a login prompt when every session is taken. +NO_FREE_SESSION = "Sorry, the maximum number of telnet sessions are active. Try again later.\r\n" + + +def _telnet_refused(greeting: str): + def connect(**kwargs): + if kwargs["device_type"] != ProcurveDriver.NETMIKO_DEVICE_TYPE_TELNET: + raise OSError("no route to host") + kwargs["session_log"].write(greeting) + raise NetmikoAuthenticationException(f"Login failed: {kwargs['host']}") + + return connect + + +def _open(connect, **optional_args) -> ConnectionException: + driver = ProcurveDriver("10.0.0.40", "manager", "s3cret", optional_args=optional_args) + with patch(PROBE, return_value=(None, None)), patch(HANDLER, side_effect=connect): + with pytest.raises(ConnectionException) as exc_info: + driver.open() + return exc_info.value + + +# --- Telnet ----------------------------------------------------------------- + + +def test_no_free_telnet_session_is_a_connection_error_not_a_wrong_password(): + error = _open(_telnet_refused(NO_FREE_SESSION)) + + msg = str(error) + assert "Authentication failed" not in msg + assert "telnet: the switch has no free session (maximum number of telnet sessions" in msg + + +def test_a_refused_telnet_login_is_still_an_authentication_failure(): + error = _open(_telnet_refused("Password: \r\nInvalid password\r\n")) + + assert "Authentication failed for 10.0.0.40 via telnet" in str(error) + + +def test_the_telnet_transcript_records_what_the_switch_sent_not_the_password(): + sessions: list = [] + + def connect(**kwargs): + sessions.append(kwargs["session_log"]) + return MagicMock() + + driver = ProcurveDriver("10.0.0.40", "manager", "s3cret", optional_args={"transport": "telnet"}) + with patch(HANDLER, side_effect=connect): + driver.open() + + assert sessions[0].record_writes is False + + +# --- SSH -------------------------------------------------------------------- + + +def _wrapped(cause: Exception) -> NetmikoTimeoutException: + """What netmiko raises: its own exception, the paramiko or socket error as context.""" + exc = NetmikoTimeoutException("A paramiko SSHException occurred during connection creation") + exc.__context__ = cause + return exc + + +def test_an_ssh_key_exchange_failure_is_named_not_reported_as_a_timeout(): + no_kex = paramiko.ssh_exception.IncompatiblePeer( + "Incompatible ssh peer (no acceptable kex algorithm)" + ) + + def connect(**kwargs): + if kwargs["device_type"] == ProcurveDriver.NETMIKO_DEVICE_TYPE_TELNET: + raise OSError("no route to host") + raise _wrapped(no_kex) + + msg = str(_open(connect)) + + assert "ssh: Incompatible ssh peer (no acceptable kex algorithm)" in msg + assert "ssh: timed out" not in msg + + +def test_an_ssh_timeout_is_still_reported_as_one(): + def connect(**kwargs): + if kwargs["device_type"] == ProcurveDriver.NETMIKO_DEVICE_TYPE_TELNET: + raise OSError("no route to host") + raise _wrapped(TimeoutError("timed out")) + + assert "ssh: timed out" in str(_open(connect)) + + +# --- REST ------------------------------------------------------------------- + + +def _client_answering(status: int, content_type: str) -> ProcurveApiClient: + client = ProcurveApiClient("10.0.0.40", "manager", "s3cret") + client.setup("v7", "https") + response = MagicMock(status_code=status, headers={"Content-Type": content_type}) + session = MagicMock() + session.post.return_value = response + session.headers = {} + with patch("napalm_procurve.api_client.requests.Session", return_value=session): + client.connect() + return client + + +def test_a_web_page_instead_of_a_rest_answer_is_not_a_login_failure(): + with pytest.raises(ConnectionException) as exc_info: + _client_answering(200, "text/html; charset=utf-8") + + assert not isinstance(exc_info.value, ConnectAuthError) + assert str(exc_info.value) == ( + "REST API on 10.0.0.40 answered with a web page instead of JSON (HTTP 200)" + ) + + +def test_a_refused_rest_login_is_still_an_authentication_failure(): + with pytest.raises(ConnectAuthError, match=r"REST API login failed \(HTTP 401\)"): + _client_answering(401, "application/json") + + +def test_the_transcript_keeps_the_greeting_not_the_whole_session(): + from napalm_procurve.connect_reasons import TelnetTranscript + + transcript = TelnetTranscript() + transcript.write(NO_FREE_SESSION) + for _ in range(1000): + transcript.write("show running-config output\r\n" * 10) + + assert transcript.no_free_session + assert len(transcript.text) < 10_000 From b26584c7da550b8fdfd6fcfd2728131414731f24 Mon Sep 17 00:00:00 2001 From: Christian Manivong Date: Sun, 1 Nov 2026 21:51:06 +0100 Subject: [PATCH 3/5] fix(snmp): read the communities over the REST API too get_snmp_config sent "show snmp-server" through the CLI session, which does not exist on the REST transport, and returned None, so every switch managed over REST read as "SNMP not configured". Over REST the command now runs through the API's /cli endpoint and the output goes through the parser the SSH path uses. A failed REST read raises. Closes #10 --- CHANGELOG.md | 3 ++ napalm_procurve/procurve.py | 72 +++++++++++++------------- tests/quality_baseline.json | 6 +-- tests/unit/test_snmp_config.py | 93 ++++++++++++++++++++++++++++++++++ 4 files changed, 132 insertions(+), 42 deletions(-) create mode 100644 tests/unit/test_snmp_config.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 6886adf..db407ff 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -27,6 +27,9 @@ All notable changes to this driver. The format follows web page instead of JSON", not as a failed login. - An SSH attempt that failed for another reason than a timeout, such as no common key exchange algorithm, names that reason instead of "timed out". +- `get_snmp_config` reads the switch's communities over the REST API too. It returned + `None` there, so a switch managed over REST always read as having no SNMP. A read that + fails now raises instead of reading as "no SNMP" (REST transport). ## [0.6.0] - 2026-10-23 diff --git a/napalm_procurve/procurve.py b/napalm_procurve/procurve.py index 57d439f..4c7dbfc 100644 --- a/napalm_procurve/procurve.py +++ b/napalm_procurve/procurve.py @@ -15,6 +15,7 @@ A specific transport can be forced with ``optional_args={"transport": "ssh"}``. Netmiko device type: ``hp_procurve`` / ``hp_procurve_telnet`` """ +import base64 import logging import re from typing import Any, ClassVar @@ -34,7 +35,7 @@ from napalm_device_types import ( add_lag_interfaces, run_fix_steps, ) -from napalm_device_types.models import InterfaceConfigDict, VlanConfigDict +from napalm_device_types.models import InterfaceConfigDict, SNMPConfigDict, VlanConfigDict from napalm_device_types.ssh_host_keys import ( KNOWN_KEYS_ARG, OBSERVER_ARG, @@ -1204,47 +1205,42 @@ class ProcurveDriver(ConfigLifecycleMixin, SwitchDriver): """Return device warnings. SNMP detection handled by poll task.""" return [] - def get_snmp_config(self): - """Return SNMP config if a community is configured on the switch.""" - try: - from napalm_device_types.models import SNMPConfigDict - except ImportError: - return None + def get_snmp_config(self) -> SNMPConfigDict | None: + """The community of the built-in agent, read-only preferred; None without one. - # Use a single command with short read_timeout to avoid blocking the poll. - try: - out = ( - self._device.send_command( - "show snmp-server", - expect_string=rf"{re.escape(self._device.base_prompt)}[>#]", - read_timeout=10, - ).strip() - if self._device - else "" - ) - except Exception: + Over REST, ``show snmp-server`` runs through the API's ``/cli`` endpoint (#10). + """ + if self._transport == "api": + out = self._api_show("show snmp-server") + else: + # Use a single command with short read_timeout to avoid blocking the poll. + try: + out = ( + self._device.send_command( + "show snmp-server", + expect_string=rf"{re.escape(self._device.base_prompt)}[>#]", + read_timeout=10, + ) + if self._device + else "" + ) + except Exception: + return None + communities = parsers.parse_snmp_info(out)["community"] + if not communities: return None - if not out: - return None - - # Parse communities from output - community = None - for line in out.splitlines(): - m = re.match(r"\s+(\S+)\s+(Manager|Operator)\s+(Restricted|Unrestricted)", line, re.I) - if m: - comm = m.group(1) - access = m.group(3).lower() - if access == "restricted": # read-only — prefer this - community = comm - break - elif community is None: - community = comm # fallback to first found - - if not community: - return None - + read_only = [name for name, c in communities.items() if c["mode"] == "ro"] + community = (read_only or list(communities))[0] return SNMPConfigDict(running=True, community=community, port=161, version="2c") + def _api_show(self, command: str) -> str: + """The output of a show command through the REST API's ``/cli`` endpoint.""" + resp = self._api.post("cli", json={"cmd": command}) + if not resp.ok or resp.json().get("status") == "CCS_FAILURE": + raise CommandErrorException(f"{command!r} over REST: HTTP {resp.status_code}") + encoded = resp.json().get("result_base64_encoded", "") + return base64.b64decode(encoded).decode("utf-8", "replace") + # ------------------------------------------------------------------ # SNMP agent (napalm-device-types SnmpAgentMixin): the caller's values # ------------------------------------------------------------------ diff --git a/tests/quality_baseline.json b/tests/quality_baseline.json index bc105ba..2185629 100644 --- a/tests/quality_baseline.json +++ b/tests/quality_baseline.json @@ -27,9 +27,7 @@ "napalm_procurve.procurve" ], "python_file_lines": { - "napalm_procurve/procurve.py": 1396 + "napalm_procurve/procurve.py": 1392 }, - "untyped_public": [ - "napalm_procurve/procurve.py::ProcurveDriver.get_snmp_config" - ] + "untyped_public": [] } diff --git a/tests/unit/test_snmp_config.py b/tests/unit/test_snmp_config.py new file mode 100644 index 0000000..5d49e33 --- /dev/null +++ b/tests/unit/test_snmp_config.py @@ -0,0 +1,93 @@ +"""get_snmp_config reads the switch's communities over every transport (#10). + +Over the REST API there is no CLI session, so the getter returned None and a +switch managed over REST always read as "SNMP not configured". The API's +``/cli`` endpoint runs ``show snmp-server`` and answers with the output in +base64, which the SSH path's parser reads. +""" + +from __future__ import annotations + +import base64 +from unittest.mock import MagicMock + +import pytest +from napalm.base.exceptions import CommandErrorException + +from napalm_procurve.procurve import ProcurveDriver + +SHOW_SNMP_SERVER = """\ + + Community Names + + Community Name MIB View Write Access + -------------------------------- -------- ------------ + private Manager Unrestricted + c0mm Manager Restricted + + Trap Receivers + + Link-Change Traps Enabled on Ports [All] : All +""" + +NO_COMMUNITY = """\ + + Community Names + + Community Name MIB View Write Access + -------------------------------- -------- ------------ +""" + + +def _cli_answer(output: str, status: str = "CCS_SUCCESS", http: int = 200) -> MagicMock: + resp = MagicMock(ok=200 <= http < 300, status_code=http, text="") + resp.json.return_value = { + "cmd": "show snmp-server", + "result_base64_encoded": base64.b64encode(output.encode()).decode(), + "status": status, + } + return resp + + +def _rest_driver(resp: MagicMock) -> ProcurveDriver: + driver = ProcurveDriver("10.0.0.40", "manager", "s3cret") + driver._transport = "api" + driver._api = MagicMock() + driver._api.post.return_value = resp + return driver + + +def test_over_rest_the_read_only_community_is_read_through_the_cli_endpoint(): + driver = _rest_driver(_cli_answer(SHOW_SNMP_SERVER)) + + config = driver.get_snmp_config() + + assert config == {"running": True, "community": "c0mm", "port": 161, "version": "2c"} + driver._api.post.assert_called_once_with("cli", json={"cmd": "show snmp-server"}) + + +def test_over_rest_a_switch_without_a_community_has_no_snmp_config(): + assert _rest_driver(_cli_answer(NO_COMMUNITY)).get_snmp_config() is None + + +@pytest.mark.parametrize( + "resp", + [_cli_answer("", http=401), _cli_answer("Invalid input: snmp-server", status="CCS_FAILURE")], +) +def test_over_rest_a_failed_read_raises_instead_of_reading_as_no_snmp(resp): + with pytest.raises(CommandErrorException, match="show snmp-server"): + _rest_driver(resp).get_snmp_config() + + +def test_over_ssh_the_read_only_community_is_preferred(): + driver = ProcurveDriver("10.0.0.40", "manager", "s3cret") + driver._transport = "ssh" + driver._device = MagicMock(base_prompt="swt") + driver._device.send_command.return_value = SHOW_SNMP_SERVER + + assert driver.get_snmp_config() == { + "running": True, + "community": "c0mm", + "port": 161, + "version": "2c", + } From 03cf40de99503bb44eb65233d1c667c6a7cbb7c0 Mon Sep 17 00:00:00 2001 From: Christian Manivong Date: Sun, 1 Nov 2026 22:16:51 +0100 Subject: [PATCH 4/5] test(snmp): use the recorded show snmp-server The #10 tests read a hand-written show snmp-server. They now read the output recorded from a ProCurve switch: as the CLI prints it, and as the REST /cli endpoint answers it, base64 with a trailing NUL byte. The trap receiver's address is replaced. The read-only preference and the no-community case put a line into, or take one out of, the recording. --- .../procurve-rest-cli-show-snmp-server.b64 | 1 + tests/fixtures/procurve-show-snmp-server.txt | 49 +++++++++++++++ tests/unit/test_snmp_config.py | 59 ++++++++++--------- 3 files changed, 82 insertions(+), 27 deletions(-) create mode 100644 tests/fixtures/procurve-rest-cli-show-snmp-server.b64 create mode 100644 tests/fixtures/procurve-show-snmp-server.txt diff --git a/tests/fixtures/procurve-rest-cli-show-snmp-server.b64 b/tests/fixtures/procurve-rest-cli-show-snmp-server.b64 new file mode 100644 index 0000000..cd4ea69 --- /dev/null +++ b/tests/fixtures/procurve-rest-cli-show-snmp-server.b64 @@ -0,0 +1 @@ +CiBTTk1QIENvbW11bml0aWVzCgogIENvbW11bml0eSBOYW1lICAgICAgICAgICAgICAgICAgIE1JQiBWaWV3IFdyaXRlIEFjY2VzcwogIC0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tIC0tLS0tLS0tIC0tLS0tLS0tLS0tLQogIHB1YmxpYyAgICAgICAgICAgICAgICAgICAgICAgICAgIE9wZXJhdG9yIFJlc3RyaWN0ZWQgIAogCiBUcmFwIFJlY2VpdmVycwoKICBMaW5rLUNoYW5nZSBUcmFwcyBFbmFibGVkIG9uIFBvcnRzIFtBbGxdIDogQWxsCgogIFRyYXBzIENhdGVnb3J5ICAgICAgICAgICAgICAgICAgICAgICAgICBDdXJyZW50IFN0YXR1cyAKICBfX19fX19fX19fX19fX19fX19fX19fX19fX19fX19fX19fX19fICAgX19fX19fX19fX19fX19fX19fIAogIFNOTVAgQXV0aGVudGljYXRpb24gICAgICAgICAgICAgICAgICAgOiBFeHRlbmRlZCAKICBQYXNzd29yZCBjaGFuZ2UgICAgICAgICAgICAgICAgICAgICAgIDogRW5hYmxlZCAKICBMb2dpbiBmYWlsdXJlcyAgICAgICAgICAgICAgICAgICAgICAgIDogRW5hYmxlZCAKICBQb3J0LVNlY3VyaXR5ICAgICAgICAgICAgICAgICAgICAgICAgIDogRW5hYmxlZCAKICBBdXRob3JpemF0aW9uIFNlcnZlciBDb250YWN0ICAgICAgICAgIDogRW5hYmxlZCAKICBESENQLVNub29waW5nICAgICAgICAgICAgICAgICAgICAgICAgIDogRW5hYmxlZCAKICBESENQdjYtU25vb3BpbmcgT3V0IG9mIFJlc291cmNlICAgICAgIDogRW5hYmxlZCAKICBESENQdjYtU25vb3BpbmcgRXJyYW50IFJlcGxpZXMgICAgICAgIDogRW5hYmxlZCAKICBEeW5hbWljIEFSUCBQcm90ZWN0aW9uICAgICAgICAgICAgICAgIDogRW5hYmxlZCAKICBEeW5hbWljIElQIExvY2tkb3duICAgICAgICAgICAgICAgICAgIDogRW5hYmxlZCAKICBEeW5hbWljIElQdjYgTG9ja2Rvd24gT3V0IG9mIFJlc291cmNlIDogRW5hYmxlZCAKICBEeW5hbWljIElQdjYgTG9ja2Rvd24gVmlvbGF0aW9ucyAgICAgIDogRW5hYmxlZCAKICBTdGFydHVwIENvbmZpZyBjaGFuZ2UgICAgICAgICAgICAgICAgIDogRGlzYWJsZWQKICBSdW5uaW5nIENvbmZpZyBDaGFuZ2UgICAgICAgICAgICAgICAgIDogRGlzYWJsZWQKICBNQUMgYWRkcmVzcyB0YWJsZSBjaGFuZ2VzICAgICAgICAgICAgIDogRGlzYWJsZWQKICBNQUMgQWRkcmVzcyBDb3VudCAgICAgICAgICAgICAgICAgICAgIDogRGlzYWJsZWQKCiAgTlRQLUNsaWVudCAgICAgICAgICAgICAgICAgICAgICAgICAgICA6IERpc2FibGVkCgogIEFkZHJlc3MgICAgICAgICAgICAgICAgQ29tbXVuaXR5ICAgICAgICAgICAgICBFdmVudHMgICBUeXBlICAgUmV0cnkgICBUaW1lb3V0CiAgLS0tLS0tLS0tLS0tLS0tLS0tLS0tLSAtLS0tLS0tLS0tLS0tLS0tLS0tLS0tIC0tLS0tLS0tIC0tLS0tLSAtLS0tLS0tIC0tLS0tLS0KICAxOTIuMC4yLjI1NCAgICAgICAgICAgIHB1YmxpYyAgICAgICAgICAgICAgICAgTm9uZSAgICAgdHJhcCAgIDMgICAgICAgMTUgICAgIAogCgogRXhjbHVkZWQgTUlCcwoKCiBTbm1wIFJlc3BvbnNlIFBkdSBTb3VyY2UtSVAgSW5mb3JtYXRpb24KCiAgU2VsZWN0aW9uIFBvbGljeSAgIDogcmZjMTUxNyAgICAgICAgICAgICAKCiBUcmFwIFBkdSBTb3VyY2UtSVAgSW5mb3JtYXRpb24KCiAgU2VsZWN0aW9uIFBvbGljeSAgIDogcmZjMTUxNyAgICAgICAgICAgICAKCgoA diff --git a/tests/fixtures/procurve-show-snmp-server.txt b/tests/fixtures/procurve-show-snmp-server.txt new file mode 100644 index 0000000..2ad3d64 --- /dev/null +++ b/tests/fixtures/procurve-show-snmp-server.txt @@ -0,0 +1,49 @@ + + SNMP Communities + + Community Name MIB View Write Access + -------------------------------- -------- ------------ + public Operator Restricted + + Trap Receivers + + Link-Change Traps Enabled on Ports [All] : All + + Traps Category Current Status + _____________________________________ __________________ + SNMP Authentication : Extended + Password change : Enabled + Login failures : Enabled + Port-Security : Enabled + Authorization Server Contact : Enabled + DHCP-Snooping : Enabled + DHCPv6-Snooping Out of Resource : Enabled + DHCPv6-Snooping Errant Replies : Enabled + Dynamic ARP Protection : Enabled + Dynamic IP Lockdown : Enabled + Dynamic IPv6 Lockdown Out of Resource : Enabled + Dynamic IPv6 Lockdown Violations : Enabled + Startup Config change : Disabled + Running Config Change : Disabled + MAC address table changes : Disabled + MAC Address Count : Disabled + + NTP-Client : Disabled + + Address Community Events Type Retry Timeout + ---------------------- ---------------------- -------- ------ ------- ------- + 192.0.2.254 public None trap 3 15 + + + Excluded MIBs + + + Snmp Response Pdu Source-IP Information + + Selection Policy : rfc1517 + + Trap Pdu Source-IP Information + + Selection Policy : rfc1517 + + diff --git a/tests/unit/test_snmp_config.py b/tests/unit/test_snmp_config.py index 5d49e33..d22be13 100644 --- a/tests/unit/test_snmp_config.py +++ b/tests/unit/test_snmp_config.py @@ -4,11 +4,16 @@ Over the REST API there is no CLI session, so the getter returned None and a switch managed over REST always read as "SNMP not configured". The API's ``/cli`` endpoint runs ``show snmp-server`` and answers with the output in base64, which the SSH path's parser reads. + +The fixtures are ``show snmp-server`` recorded from a ProCurve switch: as the SSH +CLI prints it, and as the REST ``/cli`` endpoint answers it (base64, ending in a +NUL byte); the trap receiver's address is replaced. """ from __future__ import annotations import base64 +from pathlib import Path from unittest.mock import MagicMock import pytest @@ -16,34 +21,31 @@ from napalm.base.exceptions import CommandErrorException from napalm_procurve.procurve import ProcurveDriver -SHOW_SNMP_SERVER = """\ +FIXTURES = Path(__file__).parent.parent / "fixtures" - Community Names +SHOW_SNMP_SERVER = (FIXTURES / "procurve-show-snmp-server.txt").read_text(encoding="utf-8") +SHOW_SNMP_SERVER_REST = (FIXTURES / "procurve-rest-cli-show-snmp-server.b64").read_text().strip() - Community Name MIB View Write Access - -------------------------------- -------- ------------ - private Manager Unrestricted - c0mm Manager Restricted +_PUBLIC = " public Operator Restricted \n" +assert SHOW_SNMP_SERVER.count(_PUBLIC) == 1 +#: The recording with a read-write community put in before the read-only one. +TWO_COMMUNITIES = SHOW_SNMP_SERVER.replace( + _PUBLIC, " private Manager Unrestricted\n" + _PUBLIC +) - Trap Receivers - - Link-Change Traps Enabled on Ports [All] : All -""" - -NO_COMMUNITY = """\ - - Community Names - - Community Name MIB View Write Access - -------------------------------- -------- ------------ -""" +#: The recording with its only community removed. +NO_COMMUNITY = SHOW_SNMP_SERVER.replace(_PUBLIC, "") -def _cli_answer(output: str, status: str = "CCS_SUCCESS", http: int = 200) -> MagicMock: +def _b64(output: str) -> str: + return base64.b64encode(output.encode()).decode() + + +def _cli_answer(encoded: str, status: str = "CCS_SUCCESS", http: int = 200) -> MagicMock: resp = MagicMock(ok=200 <= http < 300, status_code=http, text="") resp.json.return_value = { "cmd": "show snmp-server", - "result_base64_encoded": base64.b64encode(output.encode()).decode(), + "result_base64_encoded": encoded, "status": status, } return resp @@ -57,22 +59,25 @@ def _rest_driver(resp: MagicMock) -> ProcurveDriver: return driver -def test_over_rest_the_read_only_community_is_read_through_the_cli_endpoint(): - driver = _rest_driver(_cli_answer(SHOW_SNMP_SERVER)) +def test_over_rest_the_community_is_read_through_the_cli_endpoint(): + driver = _rest_driver(_cli_answer(SHOW_SNMP_SERVER_REST)) config = driver.get_snmp_config() - assert config == {"running": True, "community": "c0mm", "port": 161, "version": "2c"} + assert config == {"running": True, "community": "public", "port": 161, "version": "2c"} driver._api.post.assert_called_once_with("cli", json={"cmd": "show snmp-server"}) def test_over_rest_a_switch_without_a_community_has_no_snmp_config(): - assert _rest_driver(_cli_answer(NO_COMMUNITY)).get_snmp_config() is None + assert _rest_driver(_cli_answer(_b64(NO_COMMUNITY))).get_snmp_config() is None @pytest.mark.parametrize( "resp", - [_cli_answer("", http=401), _cli_answer("Invalid input: snmp-server", status="CCS_FAILURE")], + [ + _cli_answer("", http=401), + _cli_answer(_b64("Invalid input: snmp-server"), status="CCS_FAILURE"), + ], ) def test_over_rest_a_failed_read_raises_instead_of_reading_as_no_snmp(resp): with pytest.raises(CommandErrorException, match="show snmp-server"): @@ -83,11 +88,11 @@ def test_over_ssh_the_read_only_community_is_preferred(): driver = ProcurveDriver("10.0.0.40", "manager", "s3cret") driver._transport = "ssh" driver._device = MagicMock(base_prompt="swt") - driver._device.send_command.return_value = SHOW_SNMP_SERVER + driver._device.send_command.return_value = TWO_COMMUNITIES assert driver.get_snmp_config() == { "running": True, - "community": "c0mm", + "community": "public", "port": 161, "version": "2c", } From 1d5399e51ba50c43b92099e463252212f7888b43 Mon Sep 17 00:00:00 2001 From: Christian Manivong Date: Sun, 1 Nov 2026 22:17:59 +0100 Subject: [PATCH 5/5] fix(cli): decode the REST CLI answer Over the REST API, cli() returned the /cli endpoint's result_base64_encoded field as it came: base64 instead of the command's output. It now decodes it and drops the NUL byte the switch ends it with, in the same parser the SNMP read over REST uses. New finding, confirmed by the show snmp-server answer recorded from a ProCurve switch; no issue filed. --- CHANGELOG.md | 2 ++ napalm_procurve/parsers.py | 7 ++++++ napalm_procurve/procurve.py | 6 ++--- tests/quality_baseline.json | 2 +- tests/unit/test_cli.py | 44 +++++++++++++++++++++++++++++++++++++ 5 files changed, 56 insertions(+), 5 deletions(-) create mode 100644 tests/unit/test_cli.py diff --git a/CHANGELOG.md b/CHANGELOG.md index db407ff..5c3c0dc 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -17,6 +17,8 @@ All notable changes to this driver. The format follows a session log object, which older releases do not accept. ### Fixed +- `cli()` over the REST API returns the command's output. It returned the API's + base64 encoding of it as it came, NUL byte included. - `configure_snmp_agent` over the REST API opens its temporary SSH session on port 22. It used `optional_args["port"]`, which names the REST API's port when REST is the transport, so the SNMP setup failed on switches managed over REST. diff --git a/napalm_procurve/parsers.py b/napalm_procurve/parsers.py index 0ac1a3a..df42e47 100644 --- a/napalm_procurve/parsers.py +++ b/napalm_procurve/parsers.py @@ -7,6 +7,7 @@ command output strings. The same parsers are shared by the SSH and Telnet backends. """ +import base64 import re #: get_users' password field: the switch never shows a password, so it stays empty. @@ -927,3 +928,9 @@ def derive_port_pvids(vlans: dict[int, dict]) -> dict[str, int]: pvids[port] = 1 return pvids + + +def parse_cli_answer(answer: dict[str, str]) -> str: + """The output in a REST ``/cli`` answer: base64, the switch ends it with a NUL byte.""" + encoded = answer.get("result_base64_encoded", "") + return base64.b64decode(encoded).decode("utf-8", "replace").rstrip("\x00") diff --git a/napalm_procurve/procurve.py b/napalm_procurve/procurve.py index 4c7dbfc..e652673 100644 --- a/napalm_procurve/procurve.py +++ b/napalm_procurve/procurve.py @@ -15,7 +15,6 @@ A specific transport can be forced with ``optional_args={"transport": "ssh"}``. Netmiko device type: ``hp_procurve`` / ``hp_procurve_telnet`` """ -import base64 import logging import re from typing import Any, ClassVar @@ -1146,7 +1145,7 @@ class ProcurveDriver(ConfigLifecycleMixin, SwitchDriver): for cmd in commands: resp = self._api.post("cli", json={"cmd": cmd}) if resp.ok: - results[cmd] = resp.json().get("result_base64_encoded", "") + results[cmd] = parsers.parse_cli_answer(resp.json()) else: results[cmd] = f"Error: HTTP {resp.status_code}" return results @@ -1238,8 +1237,7 @@ class ProcurveDriver(ConfigLifecycleMixin, SwitchDriver): resp = self._api.post("cli", json={"cmd": command}) if not resp.ok or resp.json().get("status") == "CCS_FAILURE": raise CommandErrorException(f"{command!r} over REST: HTTP {resp.status_code}") - encoded = resp.json().get("result_base64_encoded", "") - return base64.b64decode(encoded).decode("utf-8", "replace") + return parsers.parse_cli_answer(resp.json()) # ------------------------------------------------------------------ # SNMP agent (napalm-device-types SnmpAgentMixin): the caller's values diff --git a/tests/quality_baseline.json b/tests/quality_baseline.json index 2185629..5afa848 100644 --- a/tests/quality_baseline.json +++ b/tests/quality_baseline.json @@ -27,7 +27,7 @@ "napalm_procurve.procurve" ], "python_file_lines": { - "napalm_procurve/procurve.py": 1392 + "napalm_procurve/procurve.py": 1390 }, "untyped_public": [] } diff --git a/tests/unit/test_cli.py b/tests/unit/test_cli.py new file mode 100644 index 0000000..e860fa7 --- /dev/null +++ b/tests/unit/test_cli.py @@ -0,0 +1,44 @@ +"""cli() over REST returns the command's output, not the API's base64 of it. + +The REST ``/cli`` endpoint answers ``{"result_base64_encoded": ...}``: the output in +base64, ending in a NUL byte. cli() returned that string as it came. +""" + +from __future__ import annotations + +from pathlib import Path +from unittest.mock import MagicMock + +from napalm_procurve.procurve import ProcurveDriver + +FIXTURES = Path(__file__).parent.parent / "fixtures" + +SHOW_SNMP_SERVER = (FIXTURES / "procurve-show-snmp-server.txt").read_text(encoding="utf-8") +SHOW_SNMP_SERVER_REST = (FIXTURES / "procurve-rest-cli-show-snmp-server.b64").read_text().strip() + + +def _rest_driver(resp: MagicMock) -> ProcurveDriver: + driver = ProcurveDriver("10.0.0.40", "manager", "s3cret") + driver._transport = "api" + driver._api = MagicMock() + driver._api.post.return_value = resp + return driver + + +def test_over_rest_cli_returns_the_decoded_output(): + resp = MagicMock(ok=True, status_code=200) + resp.json.return_value = { + "cmd": "show snmp-server", + "result_base64_encoded": SHOW_SNMP_SERVER_REST, + "status": "CCS_SUCCESS", + } + + out = _rest_driver(resp).cli(["show snmp-server"]) + + assert out == {"show snmp-server": SHOW_SNMP_SERVER} + + +def test_over_rest_cli_names_a_failed_request(): + resp = MagicMock(ok=False, status_code=401) + + assert _rest_driver(resp).cli(["show version"]) == {"show version": "Error: HTTP 401"}