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:
commit
586632efe0
13 files changed
+517
-75
No files matched your search
@@ -141,10 +141,7 @@ class ProcurveApiClient:
|
||||
json={"userName": self.username, "password": self.password},
|
||||
timeout=self.timeout,
|
||||
)
|
||||
if resp.status_code != 201:
|
||||
raise ConnectAuthError(
|
||||
f"REST API login failed (HTTP {resp.status_code}) for {self.hostname}"
|
||||
)
|
||||
self._require_login(resp)
|
||||
# AOS-Switch returns the session cookie in the JSON body rather than
|
||||
# via Set-Cookie — it must be sent back as a Cookie header on every
|
||||
# subsequent request, otherwise writes (POST/PUT/DELETE) are rejected
|
||||
@@ -156,6 +153,19 @@ class ProcurveApiClient:
|
||||
if check is not None:
|
||||
check.observe()
|
||||
|
||||
def _require_login(self, resp: requests.Response) -> None:
|
||||
"""Raise unless *resp* is a successful login."""
|
||||
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}"
|
||||
)
|
||||
|
||||
def _open_session(
|
||||
self, certificate_args: Mapping[str, Any] | None, check_timeout: float
|
||||
) -> CertificateCheck | None:
|
||||
|
||||
@@ -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__
|
||||
@@ -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")
|
||||
+47
-54
@@ -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
|
||||
|
||||
Reference in new issue
Block a user