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
This commit is contained in:
Christian Manivong committed 2026-11-01 21:48:56 +01:00
1 parent 874e25a1ce
commit ee49948b2b
7 files changed
+233 -12

No files matched your search

+6
View File
@@ -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}"
+56
View File
@@ -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__
+9 -10
View File
@@ -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}")