Merge remote-tracking branch 'origin/main' into fix/lldp-keyvalue
driver / standard (pull_request) Successful in 18s
driver / lint (pull_request) Successful in 20s
driver / types (pull_request) Successful in 1m8s
driver / test (3.13) (pull_request) Successful in 58s
driver / test (3.12) (pull_request) Successful in 1m6s
driver / lowest (pull_request) Successful in 29s
driver / build (pull_request) Successful in 27s
driver / security (pull_request) Successful in 1m3s
CI / driver (pull_request) Successful in 2m21s
driver / publish (pull_request) Skipped

# Conflicts:
#	CHANGELOG.md
#	tests/quality_baseline.json
This commit is contained in:
Christian Manivong committed 2026-11-02 09:29:09 +01:00
commit c7317925ed
8 files changed
+614 -40

No files matched your search

+18
View File
@@ -3,6 +3,7 @@
from __future__ import annotations
import re
from shlex import quote
from typing import Any
#: iputils: ``5 packets transmitted, 5 received, +2 errors, 0% packet loss, time 4005ms``;
@@ -21,6 +22,23 @@ _RTT = re.compile(
_PROBE = re.compile(r"bytes from (?:\S+ \()?([^\s()]+?)\)?: .*?\btime=([\d.]+) ?ms")
def ping_command(
destination: str, source: str, ttl: int, timeout: int, size: int, count: int
) -> str:
"""The shell line that pings *destination*: the names quoted, the numbers numbers (#55).
:raises ValueError: for a count, timeout, size or ttl that is no number, and for a
destination or source that ping would read as an option (#63): no address or
hostname starts with ``-``.
"""
for name in (destination, source):
if name.startswith("-"):
raise ValueError(f"{name!r} would be read as a ping option, not an address")
numbers = f"-c {int(count)} -W {int(timeout)} -s {int(size)} -t {int(ttl)}"
src_opt = f" -I {quote(source)}" if source else ""
return f"ping {numbers}{src_opt} {quote(destination)} 2>&1"
def parse_ping(output: str) -> dict[str, Any]:
"""``{"success": {...}}`` for *output* with a summary line, else ``{"error": output}``."""
summary = _SUMMARY.search(output)
+67 -13
View File
@@ -12,39 +12,93 @@ IP_ROUTE_COMMANDS = {"ipv4": "ip -4 route show", "ipv6": "ip -6 route show"}
_DEFAULT = {"ipv4": "0.0.0.0/0", "ipv6": "::/0"}
_HOST_PREFIX = {"ipv4": "/32", "ipv6": "/128"}
_VIA = re.compile(r"via\s+(\S+)")
#: The route types ``ip route`` prints in front of the destination; a unicast route
#: carries none (#57).
_ROUTE_TYPES = frozenset(
{
"unicast",
"local",
"broadcast",
"anycast",
"multicast",
"blackhole",
"unreachable",
"prohibit",
"throw",
"nat",
"xresolve",
}
)
#: Route types that send nothing out of an interface: no next hop, and no outgoing
#: interface either, though IPv6 names ``lo`` for them.
_NO_FORWARDING = frozenset({"blackhole", "unreachable", "prohibit", "throw"})
#: The line a multipath route's next hops start with, one each, after the route.
_NEXTHOP = "nexthop"
#: ``via 192.0.2.1``, or with the gateway's family in front: ``via inet6 fe80::1`` for an
#: IPv4 route with an IPv6 next hop (RFC 8950, #65).
_VIA = re.compile(r"via\s+(?:inet6?\s+)?(\S+)")
_DEV = re.compile(r"dev\s+(\S+)")
_PROTO = re.compile(r"proto\s+(\S+)")
_METRIC = re.compile(r"metric\s+(\d+)")
class IpRoute(NamedTuple):
"""One line of ``ip route show``."""
"""One route of ``ip route show``; a multipath route is one per next hop."""
network: str
proto: str
nexthop: str
iface: str
metric: int
route_type: str = "unicast"
@property
def attributes(self) -> dict[str, str]:
"""NAPALM's ``protocol_attributes`` for this route: its type, unless unicast."""
return {} if self.route_type == "unicast" else {"type": self.route_type}
def parse_ip_route(out: str, family: str) -> Iterator[IpRoute]:
"""The routes in *out*, the output of ``IP_ROUTE_COMMANDS[family]``."""
route = ""
hops: list[str] = []
for line in out.splitlines():
line = line.strip()
if not line or line.startswith("#"):
continue
dest = line.split(None, 1)[0]
network = _DEFAULT[family] if dest == "default" else dest
if "/" not in network:
network += _HOST_PREFIX[family]
yield IpRoute(
network,
_first(_PROTO, line) or "kernel",
_first(_VIA, line),
_first(_DEV, line),
int(_first(_METRIC, line) or 0),
)
if line.split(None, 1)[0] == _NEXTHOP:
hops.append(line)
continue
if route:
yield from _routes(route, hops, family)
route, hops = line, []
if route:
yield from _routes(route, hops, family)
def with_length(prefix: str) -> str:
"""*prefix* with a prefix length: a host route without one is ``/32`` or ``/128``
by the address's family (#64)."""
if "/" in prefix:
return prefix
return prefix + _HOST_PREFIX["ipv6" if ":" in prefix else "ipv4"]
def _routes(line: str, hops: list[str], family: str) -> Iterator[IpRoute]:
"""The route *line* with its multipath next-hop lines *hops*: one per next hop."""
words = line.split()
route_type = words.pop(0) if words[0] in _ROUTE_TYPES and len(words) > 1 else "unicast"
network = _DEFAULT[family] if words[0] == "default" else words[0]
if "/" not in network:
network += _HOST_PREFIX[family]
proto = _first(_PROTO, line) or "kernel"
metric = int(_first(_METRIC, line) or 0)
if route_type in _NO_FORWARDING:
yield IpRoute(network, proto, "", "", metric, route_type)
return
for hop in hops or [line]:
yield IpRoute(network, proto, _first(_VIA, hop), _first(_DEV, hop), metric, route_type)
def _first(pattern: re.Pattern[str], line: str) -> str:
+19
View File
@@ -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``;
+18 -22
View File
@@ -78,9 +78,9 @@ from netmiko.exceptions import NetmikoAuthenticationException, NetmikoTimeoutExc
from napalm_linux._dpkg import DPKG_QUERY_COMMAND, parse_dpkg_query
from napalm_linux._hostname import HostnameMixin
from napalm_linux._local_accounts import LinuxLocalAccountsMixin
from napalm_linux._ping import parse_ping
from napalm_linux._routes import IP_ROUTE_COMMANDS, parse_ip_route
from napalm_linux._shell import expect_for, prepare_shell
from napalm_linux._ping import parse_ping, ping_command
from napalm_linux._routes import IP_ROUTE_COMMANDS, IpRoute, parse_ip_route, with_length
from napalm_linux._shell import expect_for, prepare_shell, sudo_without_password
from napalm_linux._sudo_history import LinuxSudoHistoryMixin
logger = logging.getLogger("napalm_linux")
@@ -519,14 +519,14 @@ class LinuxDriver(
return self._run_privileged(command, timeout)
def _run_privileged(self, command: str, timeout: float = 100) -> str:
"""Run *command* as root: directly for a root login, through ``_sudo``
with a sudo password, and through ``sudo -n`` without one -- which fails at
once where a password prompt would hang the session until the timeout."""
"""Run all of *command* as root: directly for a root login, through ``_sudo``
with a sudo password, and through ``sudo -n sh -c`` without one -- which fails
at once where a password prompt would hang the session until the timeout."""
if self._is_root():
return self._send(command, read_timeout=timeout)
if self._sudo_password:
return self._sudo(command, read_timeout=timeout) # never typed into the shell
return self._send(f"sudo -n {command}", read_timeout=timeout)
return self._send(sudo_without_password(command), read_timeout=timeout)
# ------------------------------------------------------------------
# Command channel (napalm-device-types CommandChannelMixin)
@@ -913,7 +913,7 @@ class LinuxDriver(
def _make_entry(
proto: str, nexthop: str, iface: str, metric: int, network: str
) -> dict[str, Any]:
family = "ipv6" if (":" in network or (nexthop and ":" in nexthop)) else "ipv4"
family = "ipv6" if ":" in network else "ipv4" # not the next hop's (#65)
return {
"protocol": proto,
"family": family,
@@ -928,19 +928,19 @@ class LinuxDriver(
"protocol_attributes": {},
}
def _add(network: str, proto: str, nexthop: str, iface: str, metric: int) -> None:
if destination and network != destination:
def _add(route: IpRoute) -> None:
if destination and route.network != destination:
return
mapped = proto_map.get(proto, proto)
mapped = proto_map.get(route.proto, route.proto)
if protocol and mapped != protocol.lower():
return
routes.setdefault(network, []).append(
_make_entry(mapped, nexthop, iface, metric, network)
)
entry = _make_entry(mapped, route.nexthop, route.iface, route.metric, route.network)
entry["protocol_attributes"] = route.attributes
routes.setdefault(route.network, []).append(entry)
for family, command in IP_ROUTE_COMMANDS.items():
for route in parse_ip_route(self._send(command), family):
_add(*route)
_add(route)
# FRR/Zebra enrichment via vtysh — properly attributes OSPF/BGP/RIP protocols.
# FRR installs routes into the kernel as "proto zebra"; vtysh gives the real source.
@@ -969,12 +969,10 @@ class LinuxDriver(
if not vm:
continue
code = vm.group(1)
prefix = vm.group(2)
prefix = with_length(vm.group(2))
metric = int(vm.group(4))
nexthop = vm.group(5) or ""
iface = (vm.group(6) or "").rstrip(",")
if "/" not in prefix:
prefix += "/32"
mapped_proto = _frr_code.get(code, code.lower())
if prefix in routes:
for entry in routes[prefix]:
@@ -1066,10 +1064,8 @@ class LinuxDriver(
count: int = 5,
vrf: str = "",
) -> dict[str, Any]:
"""Execute ping from the remote host."""
src_opt = f"-I {source}" if source else ""
cmd = f"ping -c {count} -W {timeout} -s {size} -t {ttl} {src_opt} {destination} 2>&1"
return parse_ping(self._send(cmd))
"""Ping from the remote host; ValueError for a bad number or a name starting with -."""
return parse_ping(self._send(ping_command(destination, source, ttl, timeout, size, count)))
# ------------------------------------------------------------------
# KernelFactsMixin – the transport for get_kernel_facts