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
48 lines
1.9 KiB
Python
48 lines
1.9 KiB
Python
"""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,
|
|
}
|
|
}
|