Files
napalm-hpe-aruba-procurve/napalm_procurve/connect_reasons.py
T
Christian Manivong ee49948b2b 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
2026-11-01 21:48:56 +01:00

57 lines
2.0 KiB
Python

# 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__