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