fix(sudo): run the whole command as root without a sudo password
Without a root login and without a sudo password, _run_privileged typed "sudo -n <command>" into the interactive shell. sudo covered only the first simple command of the line, and dnf's and yum's advisory query, which starts with a brace group, did not parse at all: no status marker ever arrived, so netmiko waited out the 120 s read timeout and get_available_updates() failed. This is the default path for netOrk's own NOPASSWD account. The command now goes to "sudo -n sh -c" as one argument, as _as_root already does with a password. A status echo at its end stays outside sh -c: it reports sh's status, which is the command's, and still arrives when sudo refuses. Closes #56
This commit is contained in:
1 parent
c2d7c4d1b4
commit
d3134c83b8
5 files changed
+232
-7
No files matched your search
@@ -4,6 +4,7 @@ from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import re
|
||||
from shlex import quote
|
||||
from typing import Any
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
@@ -17,6 +18,10 @@ PROMPT_RE = r"[#$\>]\s*$"
|
||||
#: 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.
|
||||
@@ -35,6 +40,20 @@ def expect_for(command: str) -> str:
|
||||
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}"
|
||||
|
||||
|
||||
#: 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``;
|
||||
|
||||
Reference in new issue
Block a user