driver / standard (pull_request) Successful in 17s
driver / lint (pull_request) Successful in 14s
driver / types (pull_request) Successful in 1m10s
driver / test (3.12) (pull_request) Successful in 1m8s
driver / lowest (pull_request) Successful in 37s
driver / test (3.13) (pull_request) Successful in 1m14s
driver / build (pull_request) Successful in 38s
driver / security (pull_request) Successful in 1m20s
CI / driver (pull_request) Successful in 2m59s
driver / publish (pull_request) Skipped
get_route_to read "ip -4 route show && ip -6 route show" as one output and mapped "default" to 0.0.0.0/0; the "default6" branch meant for IPv6 never matches, because ip -6 also prints "default". A dual-stack host showed two 0.0.0.0/0 routes, one of them family ipv6. Each family is now read with its own command, so "default" becomes ::/0 for IPv6 and a host route without a prefix length a /128 there instead of a /32. The line parse moves to napalm_linux/_routes.py. Closes #6
53 lines
1.6 KiB
Python
53 lines
1.6 KiB
Python
"""Routes from ``ip route show``, one address family at a time."""
|
|
|
|
from __future__ import annotations
|
|
|
|
import re
|
|
from collections.abc import Iterator
|
|
from typing import NamedTuple
|
|
|
|
#: The command per family. ``ip -6 route show`` names its default route ``default``
|
|
#: as well, so only the command a line came from says which family it is (#6).
|
|
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+)")
|
|
_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``."""
|
|
|
|
network: str
|
|
proto: str
|
|
nexthop: str
|
|
iface: str
|
|
metric: int
|
|
|
|
|
|
def parse_ip_route(out: str, family: str) -> Iterator[IpRoute]:
|
|
"""The routes in *out*, the output of ``IP_ROUTE_COMMANDS[family]``."""
|
|
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),
|
|
)
|
|
|
|
|
|
def _first(pattern: re.Pattern[str], line: str) -> str:
|
|
match = pattern.search(line)
|
|
return match.group(1) if match else ""
|