Merge remote-tracking branch 'origin/main' into fix/rest-cert-tofu-17

The REST login now checks the certificate before it posts the password
(#17) and then tells a web page from a refused login (#13); the two
login-answer checks moved into _require_login so connect() stays within
the function-length limit. #13's REST tests stand in for the switch's
certificate, since connect() fetches it before the login.
This commit is contained in:
Christian Manivong committed 2026-11-02 00:37:11 +01:00
commit 586632efe0
13 files changed
+517 -75

No files matched your search

+47 -54
View File
@@ -34,7 +34,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,
@@ -43,13 +43,11 @@ from napalm_device_types.ssh_host_keys import (
)
from napalm_device_types.tls_certificates import CertificateCheck, TlsCertificateMismatch
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 HTTPS_PORT, ProcurveApiClient
from napalm_procurve.connect_reasons import NO_FREE_TELNET_SESSION, TelnetTranscript, failure_reason
logger = logging.getLogger("napalm_procurve")
@@ -80,6 +78,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"#]+$')
@@ -359,18 +358,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,
@@ -380,13 +376,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}")
@@ -660,11 +660,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:
@@ -1143,7 +1142,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
@@ -1202,47 +1201,41 @@ 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}")
return parsers.parse_cli_answer(resp.json())
# ------------------------------------------------------------------
# SNMP agent (napalm-device-types SnmpAgentMixin): the caller's values
# ------------------------------------------------------------------
@@ -1251,7 +1244,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"}),
@@ -1266,7 +1259,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