"""NAPALM's ``ping()`` reply from what ``ping(8)`` prints: iputils and BusyBox, IPv4 and IPv6."""
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``;
#: 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
:`` or, for a name, ``bytes from ():``.
#: 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 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)
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,
}
}