fix(ping): read BusyBox's ping and IPv6 replies

ping() only knew the iputils summary. BusyBox, the ping on Alpine,
writes "2 packets received", so every target came back as an error and
the ping sweep counted it as down. Its probe lines ("seq=") and every
IPv6 reply were dropped by an IPv4-only per-probe pattern, and its
"round-trip min/avg/max" line without a deviation was not read.

The parse moves to napalm_linux/_ping.py and accepts both summaries
(also iputils' with "+N errors"), both RTT lines, IPv6 and named
replies. The shared Unix ping parser is still open as
NAPALM/napalm-device-types#12.

Closes #15
This commit is contained in:
Christian Manivong committed 2026-11-01 21:49:28 +01:00
1 parent 024f68c543
commit 69f1701ea6
5 files changed
+149 -41

No files matched your search

+6
View File
@@ -65,6 +65,12 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
dpkg still keeps (state `rc`) (#17). They were reported as installed: old kernels, or
an agent that had been removed. A package that is held, unpacked or half-configured
still counts, since its files are on disk.
- `ping()` reads BusyBox's output, the `ping` on Alpine (#15). Its summary says
"2 packets received", which did not match, so every target came back as an error and
a LAN scan through an Alpine host found nothing. Replies to IPv6 targets, BusyBox's
`seq=` replies and replies from a name (`bytes from host (address)`) now appear in
`results`, BusyBox's `round-trip` line fills the RTT fields, and an iputils summary
that counts errors is read as well.
## [0.15.1] - 2026-10-23
+47
View File
@@ -0,0 +1,47 @@
"""NAPALM's ``ping()`` reply from what ``ping(8)`` prints: iputils and BusyBox, IPv4 and IPv6."""
from __future__ import annotations
import re
from typing import Any
#: iputils: ``5 packets transmitted, 5 received, +2 errors, 0% packet loss, time 4005ms``;
#: BusyBox: ``2 packets transmitted, 2 packets received, 0% packet loss`` (#15).
_SUMMARY = re.compile(
r"(\d+) packets transmitted, (\d+) (?:packets )?received,(?: [^,]*,)*? ([\d.]+)% packet loss"
)
#: iputils: ``rtt min/avg/max/mdev = 0.1/0.2/0.3/0.05 ms``;
#: BusyBox: ``round-trip min/avg/max = 0.1/0.2/0.3 ms``, without a deviation.
_RTT = re.compile(
r"(?:rtt|round-trip) min/avg/max(?:/\w+)? = ([\d.]+)/([\d.]+)/([\d.]+)(?:/([\d.]+))? ms"
)
#: One reply: ``bytes from <address>:`` or, for a name, ``bytes from <name> (<address>):``.
#: The address may be IPv6 (``2001:db8::1``, ``fe80::1%eth0``); ``icmp_seq=`` (iputils)
#: or ``seq=`` (BusyBox), and a ``ttl=`` that is not always there, come before the time.
_PROBE = re.compile(r"bytes from (?:\S+ \()?([^\s()]+?)\)?: .*?\btime=([\d.]+) ?ms")
def parse_ping(output: str) -> dict[str, Any]:
"""``{"success": {...}}`` for *output* with a summary line, else ``{"error": output}``."""
summary = _SUMMARY.search(output)
if not summary:
return {"error": output}
sent, received = int(summary.group(1)), int(summary.group(2))
rtt = _RTT.search(output)
rtts = [float(v) if v else 0.0 for v in rtt.groups()] if rtt else [0.0] * 4
results = [
{"ip_address": probe.group(1), "rtt": float(probe.group(2))}
for probe in map(_PROBE.search, output.splitlines())
if probe
]
return {
"success": {
"probes_sent": sent,
"packet_loss": sent - received,
"rtt_min": rtts[0],
"rtt_avg": rtts[1],
"rtt_max": rtts[2],
"rtt_stddev": rtts[3],
"results": results,
}
}
+2 -39
View File
@@ -74,6 +74,7 @@ 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._shell import expect_for, prepare_shell
from napalm_linux._sudo_history import LinuxSudoHistoryMixin
@@ -1122,45 +1123,7 @@ class LinuxDriver(
"""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"
output = self._send(cmd)
# Parse summary line: "5 packets transmitted, 5 received, 0% packet loss"
m = re.search(
r"(\d+) packets transmitted,\s*(\d+) received,\s*([\d.]+)% packet loss",
output,
)
if not m:
return {"error": output}
sent, received = int(m.group(1)), int(m.group(2))
# Parse rtt line: "rtt min/avg/max/mdev = 0.123/0.456/0.789/0.100 ms"
rtt_m = re.search(r"rtt .* = ([\d.]+)/([\d.]+)/([\d.]+)/([\d.]+) ms", output)
results = []
for line in output.splitlines():
icmp_m = re.search(
r"bytes from ([\d.]+).*icmp_seq=\d+ ttl=(\d+) time=([\d.]+) ms", line
)
if icmp_m:
results.append(
{
"ip_address": icmp_m.group(1),
"rtt": float(icmp_m.group(3)),
}
)
return {
"success": {
"probes_sent": sent,
"packet_loss": sent - received,
"rtt_min": float(rtt_m.group(1)) if rtt_m else 0.0,
"rtt_avg": float(rtt_m.group(2)) if rtt_m else 0.0,
"rtt_max": float(rtt_m.group(3)) if rtt_m else 0.0,
"rtt_stddev": float(rtt_m.group(4)) if rtt_m else 0.0,
"results": results,
}
}
return parse_ping(self._send(cmd))
# ------------------------------------------------------------------
# KernelFactsMixin – the transport for get_kernel_facts
+1 -2
View File
@@ -14,7 +14,6 @@
"napalm_linux/linux.py::LinuxDriver.get_networks": 52,
"napalm_linux/linux.py::LinuxDriver.get_route_to": 138,
"napalm_linux/linux.py::LinuxDriver.get_vpn_tunnels": 152,
"napalm_linux/linux.py::LinuxDriver.ping": 52,
"napalm_linux/linux.py::LinuxDriver.search_packages": 106,
"napalm_linux/linux.py::LinuxDriver.uninstall_package": 51
},
@@ -22,7 +21,7 @@
"napalm_linux.linux"
],
"python_file_lines": {
"napalm_linux/linux.py": 2213
"napalm_linux/linux.py": 2176
},
"untyped_public": []
}
+93
View File
@@ -423,6 +423,99 @@ def test_ping_parses_output(driver):
assert result["success"]["rtt_avg"] == pytest.approx(12.1)
#: BusyBox ping (Alpine 3.22), IPv4: "packets received", "seq=", no mdev (#15).
PING_BUSYBOX = """\
PING 192.0.2.1 (192.0.2.1): 100 data bytes
108 bytes from 192.0.2.1: seq=0 ttl=64 time=0.412 ms
108 bytes from 192.0.2.1: seq=1 ttl=64 time=0.388 ms
--- 192.0.2.1 ping statistics ---
2 packets transmitted, 2 packets received, 0% packet loss
round-trip min/avg/max = 0.388/0.400/0.412 ms
"""
#: BusyBox ping, IPv6 link-local.
PING_BUSYBOX_V6 = """\
PING fe80::1%eth0 (fe80::1%eth0): 100 data bytes
108 bytes from fe80::1%eth0: seq=0 ttl=64 time=0.511 ms
--- fe80::1%eth0 ping statistics ---
2 packets transmitted, 1 packets received, 50% packet loss
round-trip min/avg/max = 0.511/0.511/0.511 ms
"""
#: iputils ping (Debian 13), IPv6.
PING_IPUTILS_V6 = """\
PING 2001:db8::53 (2001:db8::53) 100 data bytes
108 bytes from 2001:db8::53: icmp_seq=1 ttl=58 time=10.5 ms
108 bytes from 2001:db8::53: icmp_seq=2 ttl=58 time=10.9 ms
--- 2001:db8::53 ping statistics ---
2 packets transmitted, 2 received, 0% packet loss, time 1002ms
rtt min/avg/max/mdev = 10.500/10.700/10.900/0.200 ms
"""
#: iputils ping to a name: the reply names the host, the address in brackets;
#: unreachable probes add an "errors" field to the summary.
PING_IPUTILS_NAME = """\
PING gw.example.net (192.0.2.1) 100(128) bytes of data.
108 bytes from gw.example.net (192.0.2.1): icmp_seq=1 ttl=64 time=0.301 ms
From 192.0.2.254 icmp_seq=2 Destination Host Unreachable
--- gw.example.net ping statistics ---
2 packets transmitted, 1 received, +1 errors, 50% packet loss, time 1001ms
rtt min/avg/max/mdev = 0.301/0.301/0.301/0.000 ms
"""
class TestPingFormats:
"""``ping`` reads BusyBox's and iputils' output, IPv4 and IPv6 (#15)."""
def _ping(self, driver, output):
with patch.object(driver, "_send", return_value=output):
return driver.ping("192.0.2.1", count=2)["success"]
def test_busybox_summary_and_rtt(self, driver):
reply = self._ping(driver, PING_BUSYBOX)
assert (reply["probes_sent"], reply["packet_loss"]) == (2, 0)
assert (reply["rtt_min"], reply["rtt_avg"], reply["rtt_max"]) == (0.388, 0.4, 0.412)
assert reply["rtt_stddev"] == 0.0
def test_busybox_probes(self, driver):
reply = self._ping(driver, PING_BUSYBOX)
assert reply["results"] == [
{"ip_address": "192.0.2.1", "rtt": 0.412},
{"ip_address": "192.0.2.1", "rtt": 0.388},
]
def test_busybox_ipv6(self, driver):
reply = self._ping(driver, PING_BUSYBOX_V6)
assert (reply["probes_sent"], reply["packet_loss"]) == (2, 1)
assert reply["results"] == [{"ip_address": "fe80::1%eth0", "rtt": 0.511}]
def test_iputils_ipv6(self, driver):
reply = self._ping(driver, PING_IPUTILS_V6)
assert reply["results"] == [
{"ip_address": "2001:db8::53", "rtt": 10.5},
{"ip_address": "2001:db8::53", "rtt": 10.9},
]
assert (reply["rtt_avg"], reply["rtt_stddev"]) == (10.7, 0.2)
def test_iputils_to_a_name_with_errors(self, driver):
reply = self._ping(driver, PING_IPUTILS_NAME)
assert (reply["probes_sent"], reply["packet_loss"]) == (2, 1)
assert reply["results"] == [{"ip_address": "192.0.2.1", "rtt": 0.301}]
def test_no_summary_is_an_error(self, driver):
with patch.object(driver, "_send", return_value="ping: unknown host nosuch"):
assert driver.ping("nosuch") == {"error": "ping: unknown host nosuch"}
# ---------------------------------------------------------------------------
# apply_updates – input validation
# ---------------------------------------------------------------------------