Files
napalm-linux/napalm_linux/_shell.py
T
Christian Manivong 98157f3673
driver / standard (pull_request) Successful in 15s
driver / lint (pull_request) Successful in 13s
driver / types (pull_request) Successful in 55s
driver / test (3.12) (pull_request) Successful in 58s
driver / test (3.13) (pull_request) Successful in 50s
driver / lowest (pull_request) Successful in 25s
driver / build (pull_request) Successful in 26s
driver / security (pull_request) Successful in 55s
CI / driver (pull_request) Successful in 2m20s
driver / publish (pull_request) Skipped
refactor(channel): import run_on_transport from the package, as linux.py does (NetOrk/netork#818)
2026-11-17 00:17:39 +01:00

124 lines
5.2 KiB
Python

"""The interactive shell netmiko opens, made fit to be read before the first command."""
from __future__ import annotations
import logging
import re
from shlex import quote
from typing import Any
from napalm_device_types import run_on_transport
logger = logging.getLogger(__name__)
#: The end of a command's output when nothing better is known: a line that looks
#: like a shell prompt.
PROMPT_RE = r"[#$\>]\s*$"
#: A command ending in ``echo __NAME=$?`` reports its exit status on a line of its
#: own: the driver's ``_RC_MARKER``, ``__APT_RC=`` and ``__SVC_RC=`` in
#: napalm-device-types.
STATUS_ECHO_RE = re.compile(r"echo\s+(__[A-Z_]+=)\$\?")
#: The same echo as the last command of a line: ``sudo_without_password`` keeps it
#: outside sudo.
_TRAILING_STATUS_ECHO_RE = re.compile(r";\s*echo\s+__[A-Z_]+=\$\?\s*$")
def expect_for(command: str) -> str:
"""The pattern that ends *command*'s output.
netmiko stops reading as soon as the pattern matches what it has read so far.
A line the command prints can end in ``#``, ``$`` or ``>`` -- apt's
``<ftpmaster@ubuntu.com>`` after a bad signature -- and was taken for the
prompt: half the output came back, and the rest started the next command's
(#615). A command that echoes its exit status is read until that marker, with
a number, and the prompt line after it. The echoed command line carries a
literal ``$?`` and cannot match.
"""
markers: list[str] = STATUS_ECHO_RE.findall(command)
if not markers:
return PROMPT_RE
return re.escape(markers[-1]) + r"\d+\s*\n.*" + PROMPT_RE
def sudo_without_password(command: str) -> str:
"""The line that runs all of *command* as root through ``sudo -n`` (#56).
The command goes to ``sh -c`` as one argument: ``sudo -n <command>`` covered only
its first simple command, and one that starts with a brace group did not parse.
A status echo at its end stays outside and reports sh's status, the command's:
it arrives when sudo refuses as well, where netmiko would otherwise wait for it
until the read timeout.
"""
echo = _TRAILING_STATUS_ECHO_RE.search(command)
body, tail = (command[: echo.start()], echo.group()) if echo else (command, "")
return f"sudo -n sh -c {quote(body)}{tail}"
#: Whether sudo runs a command for the login user without a password now: in
#: the shape every privileged command takes (``sh -c``), so a sudoers rule that
#: covers one covers the other.
SUDO_ASKS_NOTHING = "sudo -n sh -c true"
def unprompted_stream(
transport: Any, command: str, line: str, prefix: bytes | None
) -> tuple[str, bytes | None]:
"""The line and stdin prefix a privileged stream of *command* starts with.
With a sudo password (*prefix*) sudo is asked first whether it wants it: a
sudo that does not prompt -- NOPASSWD, a cached timestamp -- would leave the
password on stdin, where the stream's own data follows it, the Podman API
over ``sudo podman system dial-stdio`` say (NetOrk/netork#818). Such a sudo
gets *command* through ``sudo -n`` and no password; one that asks gets it.
"""
if not prefix:
return line, prefix
if run_on_transport(transport, SUDO_ASKS_NOTHING, timeout=15).exit_code == 0:
return f"sudo -n sh -c {quote(command)}", None
return line, prefix
#: Sent before anything else in the interactive session (NetOrk/netork#1039):
#: the shell writes no history file and records nothing more. The leading space
#: keeps this line itself out of a history under ``HISTCONTROL=ignorespace``;
#: a shell without ``set -o history`` (dash) only complains, to /dev/null.
HISTORY_OFF = " unset HISTFILE; set +o history 2>/dev/null; true"
#: Sent right after ``HISTORY_OFF`` (#41): systemd 258's
#: ``/etc/profile.d/80-systemd-osc-context.sh`` wraps every command in OSC 3008
#: sequences from ``PS0`` and ``PROMPT_COMMAND``, each with a fresh UUID. It appends
#: to ``PROMPT_COMMAND`` as an array, so only ``unset`` removes its hook.
PROMPT_HOOKS_OFF = " unset PS0 PROMPT_COMMAND; true"
#: Keeps the PTY from wrapping long output lines (e.g. docker JSON).
NO_LINE_WRAP = "stty cols 10000 2>/dev/null || true"
def prepare_shell(device: Any, hostname: str) -> None:
"""Make netmiko's fresh shell *device* fit to read, one step at a time.
A step the shell refuses is logged and skipped: none of them is worth
failing the connection for.
"""
# No history before anything else is typed (NetOrk/netork#1039).
try:
device.send_command(HISTORY_OFF, expect_string=PROMPT_RE)
except Exception:
logger.debug("Could not switch the shell history off on %s", hostname, exc_info=True)
# No systemd OSC 3008 context around every command (#41). netmiko learned
# the prompt with those sequences in front, and a prompt carrying a fresh
# UUID never matches again, so it reads the prompt anew once they are gone.
try:
device.send_command(PROMPT_HOOKS_OFF, expect_string=PROMPT_RE)
device.set_base_prompt()
except Exception:
logger.debug("Could not switch the prompt hooks off on %s", hostname, exc_info=True)
try:
device.send_command(NO_LINE_WRAP, expect_string=PROMPT_RE)
except Exception:
logger.debug("%s: ignored", hostname, exc_info=True)