ping() typed its arguments into the interactive shell as they came, so a destination such as "1.2.3.4; id" ran the command after the semicolon as the login user. destination and source now go through shlex.quote, and count, timeout, size and ttl are coerced with int(), which refuses anything that is not a number before a command is sent. The command is built in _ping.py, next to its parser, which keeps linux.py within its recorded length. Closes #55
61 lines
2.4 KiB
Python
61 lines
2.4 KiB
Python
"""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 <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 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.
|
|
"""
|
|
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,
|
|
}
|
|
}
|