### Install pingparsing with pip Source: https://pingparsing.readthedocs.io/en/latest/pages/introduction/index.html Install the pingparsing package using pip. This is the standard installation command. ```bash pip install pingparsing ``` -------------------------------- ### PingTransmitter.deadline property Source: https://pingparsing.readthedocs.io/en/latest/_modules/pingparsing/_pingtransmitter.html Gets or sets the deadline before ping exits. Accepts a number or string with optional unit specifiers; defaults to seconds if no unit is specified. ```APIDOC ## PingTransmitter.deadline property ### Description Gets or sets the deadline before ping exits. Accepts a number or string with optional unit specifiers; defaults to seconds if no unit is specified. ### Getter Returns the current deadline as a humanreadable.Time object or None. ### Setter - **value** (TimeArg) - The deadline value. Can be a number, string, or humanreadable.Time object. If a string is provided, the default unit is seconds. ### Raises - **ValueError** - If the deadline is not greater than zero. ### Unit Specifiers | Unit | Available specifiers (str) | |------|----------------------------| | days | d, day, days | | hours | h, hour, hours | | minutes | m, min, mins, minute, minutes | | seconds | s, sec, secs, second, seconds | | milliseconds | ms, msec, msecs, millisecond, milliseconds | | microseconds | us, usec, usecs, microsecond, microseconds | ### Example python transmitter.deadline = "3sec" transmitter.deadline = 3 # seconds ``` -------------------------------- ### Execute pingparsing with single destination Source: https://pingparsing.readthedocs.io/en/latest/pages/usage/cli.html Run pingparsing against a single destination to get parsed JSON results. The output shows a JSON object keyed by destination with packet stats like packet_transmit and rtt_min. ```plaintext $ pingparsing google.com { "google.com": { "destination": "google.com", "packet_transmit": 10, "packet_receive": 10, "packet_loss_rate": 0.0, "packet_loss_count": 0, "rtt_min": 34.189, "rtt_avg": 46.054, "rtt_max": 63.246, "rtt_mdev": 9.122, "packet_duplicate_rate": 0.0, "packet_duplicate_count": 0 } } ``` -------------------------------- ### PingTransmitter.timeout property Source: https://pingparsing.readthedocs.io/en/latest/_modules/pingparsing/_pingtransmitter.html Gets or sets the timeout for each ping packet. Accepts a number or string with optional unit specifiers; defaults to milliseconds if no unit is specified. ```APIDOC ## PingTransmitter.timeout property ### Description Gets or sets the timeout for each ping packet. Accepts a number or string with optional unit specifiers; defaults to milliseconds if no unit is specified. ### Getter Returns the current timeout as a humanreadable.Time object or None. ### Setter - **value** (TimeArg) - The timeout value. Can be a number, string, or humanreadable.Time object. If a string is provided, the default unit is milliseconds. ### Raises - **ValueError** - If the timeout is not greater than zero. ### Example python transmitter.timeout = "1sec" transmitter.timeout = 1000 # milliseconds ``` -------------------------------- ### CLI help output Source: https://pingparsing.readthedocs.io/en/latest/pages/usage/cli.html Shows the full usage and options for the pingparsing command. Includes positional arguments, ping options, and output options. ```text usage: pingparsing [-h] [-V] [--max-workers MAX_WORKERS] [--timestamp {none,epoch,datetime}] [-c COUNT] [-s PACKET_SIZE] [--ttl TTL] [-w DEADLINE] [--timeout TIMEOUT] [-I INTERFACE] [--addopts OPTIONS] [--indent INDENT] [--icmp-reply] [--timezone TIMEZONE] [--no-color] [--debug | --quiet] destination_or_file [destination_or_file ...] positional arguments: destination_or_file Destinations to send ping or files to parse. '-' for parsing the standard input. options: -h, --help show this help message and exit -V, --version show program's version number and exit --max-workers MAX_WORKERS Number of threads for when multiple destinations/files are specified. Defaults to equal two times the number of cores. --debug for debug print. --quiet suppress execution log messages. Ping Options: --timestamp {none,epoch,datetime} [Only for LINUX] none: no timestamps. epoch: add timestamps with UNIX epoch time format. datetime: add timestamps with ISO time format. -c COUNT, --count COUNT Stop after sending the count. see also ping(8) [-c count] option description. -s PACKET_SIZE, --packet-size PACKET_SIZE Specifies the number of data bytes to be sent. --ttl TTL Specifies the Time to Live. -w DEADLINE, --deadline DEADLINE Timeout before ping exits. valid time units are: d/day/days, h/hour/hours, m/min/mins/minute/minutes, s/sec/secs/second/seconds, ms/msec/msecs/millisecond/milliseconds, us/usec/usecs/microsecond/microseconds. if no unit string found, considered seconds as the time unit. see also ping(8) [-w deadline] option description. note: meaning of the 'deadline' may differ system from to system. --timeout TIMEOUT Time to wait for a response per packet. Valid time units are: d/day/days, h/hour/hours, m/min/mins/minute/minutes, s/sec/secs/second/seconds, ms/msec/msecs/millisecond/milliseconds, us/usec/usecs/microsecond/microseconds. If no unit string is found, consider milliseconds as the time unit. Attempt to send packets with milliseconds granularity in default. If the system does not support timeout in milliseconds, round up as seconds. Use system default if not specified. This option will be ignored if the system does not support timeout itself. See also ping(8) [-W timeout] option description. note: meaning of the 'timeout' may differ from system to system. -I INTERFACE, --interface INTERFACE network interface --addopts OPTIONS extra command line options Output Options: --indent INDENT JSON output will be pretty-printed with the indent level. (default= 4) --icmp-reply, --icmp-replies print results for each ICMP packet reply. --timezone TIMEZONE Time zone for timestamps. --no-color Turn off colors. Documentation: https://pingparsing.rtfd.io/ Issue tracker: https://github.com/thombashi/pingparsing/issues ``` -------------------------------- ### Input ping result files (ping.txt and osx.txt) Source: https://pingparsing.readthedocs.io/en/latest/pages/usage/cli.html Sample ping output files used as input for the pingparsing command. ping.txt contains Linux-style ping statistics, while osx.txt contains macOS-style ping output with individual ICMP replies. ```text $ cat ping.txt PING 192.168.0.1 (192.168.0.1) 56(84) bytes of data. --- 192.168.0.1 ping statistics --- 1688 packets transmitted, 1553 received, +1 duplicates, 7% packet loss, time 2987ms rtt min/avg/max/mdev = 0.282/0.642/11.699/0.699 ms, pipe 2, ipg/ewma 1.770/0.782 ms $ cat osx.txt PING google.com (172.217.6.238): 56 data bytes 64 bytes from 172.217.6.238: icmp_seq=0 ttl=53 time=20.482 ms 64 bytes from 172.217.6.238: icmp_seq=1 ttl=53 time=32.550 ms 64 bytes from 172.217.6.238: icmp_seq=2 ttl=53 time=32.013 ms 64 bytes from 172.217.6.238: icmp_seq=3 ttl=53 time=28.498 ms 64 bytes from 172.217.6.238: icmp_seq=4 ttl=53 time=46.093 ms --- google.com ping statistics --- 5 packets transmitted, 5 packets received, 0.0% packet loss round-trip min/avg/max/stddev = 20.482/31.927/46.093/8.292 ms ``` -------------------------------- ### Convert PingStats to a dictionary Source: https://pingparsing.readthedocs.io/en/latest/pages/reference/parser.html Demonstrates how to parse ping results and convert the statistics into a dictionary format using as_dict(). ```python >>> import pingparsing >>> parser = pingparsing.PingParsing() >>> parser.parse(ping_result) >>> parser.as_dict() { "destination": "google.com", "packet_transmit": 60, "packet_receive": 60, "packet_loss_rate": 0.0, "packet_loss_count": 0, "rtt_min": 61.425, "rtt_avg": 99.731, "rtt_max": 212.597, "rtt_mdev": 27.566, "packet_duplicate_rate": 0.0, "packet_duplicate_count": 0 } ``` -------------------------------- ### Execute pingparsing with multiple destinations Source: https://pingparsing.readthedocs.io/en/latest/pages/usage/cli.html Run pingparsing with multiple destinations; ping executes in parallel for each. The parsed result is JSON with per-destination keys. ```plaintext $ pingparsing google.com twitter.com { "google.com": { "destination": "google.com", "packet_transmit": 10, "packet_receive": 10, "packet_loss_rate": 0.0, "packet_loss_count": 0, "rtt_min": 37.341, "rtt_avg": 44.538, "rtt_max": 53.997, "rtt_mdev": 5.827, "packet_duplicate_rate": 0.0, "packet_duplicate_count": 0 }, "twitter.com": { "destination": "twitter.com", "packet_transmit": 10, "packet_receive": 10, "packet_loss_rate": 0.0, "packet_loss_count": 0, "rtt_min": 45.377, "rtt_avg": 68.819, "rtt_max": 78.581, "rtt_mdev": 9.769, "packet_duplicate_rate": 0.0, "packet_duplicate_count": 0 } } ``` -------------------------------- ### Convert PingStats to a namedtuple Source: https://pingparsing.readthedocs.io/en/latest/pages/reference/parser.html Demonstrates how to parse ping results and convert the statistics into a namedtuple format using as_tuple(). ```python >>> import pingparsing >>> parser = pingparsing.PingParsing() >>> parser.parse(ping_result) >>> parser.as_tuple() PingResult(destination='google.com', packet_transmit=60, packet_receive=60, packet_loss_rate=0.0, packet_loss_count=0, rtt_min=61.425, rtt_avg=99.731, rtt_max=212.597, rtt_mdev=27.566, packet_duplicate_rate=0.0, packet_duplicate_count=0) ``` -------------------------------- ### Execute ping and parse result with PingTransmitter Source: https://pingparsing.readthedocs.io/en/latest/pages/usage/library.html Executes ping to google.com with count 10 using PingTransmitter, parses the output with PingParsing, and prints the result as indented JSON. The output shows the parsed statistics including packet loss rate and RTT values. ```python import json import pingparsing ping_parser = pingparsing.PingParsing() transmitter = pingparsing.PingTransmitter() transmitter.destination = "google.com" transmitter.count = 10 result = transmitter.ping() print(json.dumps(ping_parser.parse(result).as_dict(), indent=4)) ``` ```json { "destination": "google.com", "packet_transmit": 10, "packet_receive": 10, "packet_loss_rate": 0.0, "packet_loss_count": 0, "rtt_min": 34.458, "rtt_avg": 51.062, "rtt_max": 62.943, "rtt_mdev": 8.678, "packet_duplicate_rate": 0.0, "packet_duplicate_count": 0 } ``` -------------------------------- ### Construct ping command Source: https://pingparsing.readthedocs.io/en/latest/_modules/pingparsing/_pingtransmitter.html Determines the appropriate ping command maker based on the current platform and generates the command string. ```python def __make_ping_command(self) -> Command: from typing import Any # noqa maker_class: Any = None if self.__is_linux(): maker_class = LinuxPingCmdMaker elif self.__is_macos(): maker_class = MacosPingCmdMaker elif self.__is_windows(): maker_class = WindowsPingCmdMaker else: raise RuntimeError(f"not supported platform: {platform.system()}") return maker_class( count=self.count, packet_size=self.packet_size, ttl=self.ttl, deadline=self.deadline, timeout=self.timeout, interface=self.interface, is_ipv6=self.__is_ipv6(), timestamp=self.timestamp, auto_codepage=self.auto_codepage, ping_option=self.ping_option, ).make_cmd(destination=self.destination) ``` -------------------------------- ### Recommended ping command for Windows Source: https://pingparsing.readthedocs.io/en/latest/pages/usage/library.html Recommended ping command sequence for Windows to produce output suitable for parsing. It changes the code page to 437 (English) before running ping, then restores the original code page. ```batch > chcp Active code page: # get current code page > chcp 437 # change code page to english > ping -n > > chcp # restore code page ``` -------------------------------- ### Parse multiple ping result files with pingparsing Source: https://pingparsing.readthedocs.io/en/latest/pages/usage/cli.html Runs pingparsing on ping.txt and osx.txt to parse both files at once. The output is a JSON object keyed by filename, showing parsed statistics such as packet loss rate, RTT values, and duplicate counts. ```bash $ pingparsing ping.txt osx.txt { "osx.txt": { "destination": "google.com", "packet_transmit": 5, "packet_receive": 5, "packet_loss_rate": 0.0, "packet_loss_count": 0, "rtt_min": 20.482, "rtt_avg": 31.927, "rtt_max": 46.093, "rtt_mdev": 8.292, "packet_duplicate_rate": null, "packet_duplicate_count": null }, "ping.txt": { "destination": "192.168.0.1", "packet_transmit": 1688, "packet_receive": 1553, "packet_loss_rate": 7.997630331753558, "packet_loss_count": 135, "rtt_min": 0.282, "rtt_avg": 0.642, "rtt_max": 11.699, "rtt_mdev": 0.699, "packet_duplicate_rate": 0.0643915003219575, "packet_duplicate_count": 1 } } ``` -------------------------------- ### Recommended ping command for Linux Source: https://pingparsing.readthedocs.io/en/latest/pages/usage/library.html Recommended ping command for Linux to produce output suitable for parsing. It temporarily sets the locale to English (LC_ALL=C) and writes the output to a file. ```bash LC_ALL=C ping -w [option] > ``` -------------------------------- ### PingParsing class implementation Source: https://pingparsing.readthedocs.io/en/latest/_modules/pingparsing/_pingparsing.html The core class for parsing ping output, supporting Linux, Windows, macOS, and Alpine Linux formats. ```python """ .. codeauthor:: Tsuyoshi Hombashi """ from datetime import tzinfo from typing import Optional, Union import pyparsing as pp import typepy from ._common import _to_unicode from ._logger import logger from ._parser import PingParser # noqa from ._parser import ( AlpineLinuxPingParser, LinuxPingParser, MacOsPingParser, NullPingParser, WindowsPingParser, ) from ._pingtransmitter import PingResult from ._stats import PingStats from .error import ParseError, ParseErrorReason [docs] class PingParsing: """ Parser class to parsing ping command output. Args: timezone (Optional[tzinfo]): Time zone for parsing timestamps. """ def __init__(self, timezone: Optional[tzinfo] = None) -> None: self.__parser: PingParser = NullPingParser() self.__timezone = timezone @property def parser_name(self) -> str: return self.__parser._parser_name [docs] def parse(self, ping_message: Union[str, PingResult]) -> PingStats: """ Parse ping command output. Args: ping_message (str or :py:class:`~pingparsing.PingResult`): ``ping`` command output. Returns: :py:class:`~pingparsing.PingStats`: Parsed result. """ if isinstance(ping_message, PingResult): # accept PingResult instance as an input if typepy.is_not_null_string(ping_message.stdout): ping_text = ping_message.stdout else: ping_text = "" else: ping_text = ping_message logger.debug(f"parsing ping result: {ping_text}") self.__parser = NullPingParser() if typepy.is_null_string(ping_text): logger.debug("ping_message is empty") return PingStats() ping_lines = _to_unicode(ping_text).splitlines() parser_class_list = ( LinuxPingParser, WindowsPingParser, MacOsPingParser, AlpineLinuxPingParser, ) for parser_class in parser_class_list: self.__parser = parser_class(timezone=self.__timezone) # type: ignore try: return self.__parser.parse(ping_lines) except ParseError as e: if e.reason != ParseErrorReason.HEADER_NOT_FOUND: raise e except pp.ParseException: pass self.__parser = NullPingParser() return PingStats() ``` -------------------------------- ### PingTransmitter.ping() Source: https://pingparsing.readthedocs.io/en/latest/pages/reference/index.html Sends a ping to the configured destination and returns a PingResult. ```APIDOC ## PingTransmitter.ping() ### Description Sends a ping to the configured destination and returns a PingResult. ### Method ping() ### Parameters None. ### Returns PingResult object containing stdout, stderr, and returncode. ``` -------------------------------- ### PingStats.as_dict(include_icmp_replies: bool = False) -> Dict[str, str | int | float | Sequence[Dict[str, str | bool | float | int | datetime]] | None] Source: https://pingparsing.readthedocs.io/en/latest/pages/reference/parser.html Returns ping statistics as a dictionary. Can optionally include ICMP reply information. ```APIDOC ## PingStats.as_dict(include_icmp_replies: bool = False) -> Dict[str, str | int | float | Sequence[Dict[str, str | bool | float | int | datetime]] | None] ### Description Returns ping statistics. ### Parameters - **include_icmp_replies** (bool) - Optional - Whether to include ICMP reply information in the result. ### Returns - **dict** - Ping statistics. ### Example ``` >>> import pingparsing >>> parser = pingparsing.PingParsing() >>> parser.parse(ping_result) >>> parser.as_dict() { "destination": "google.com", "packet_transmit": 60, "packet_receive": 60, "packet_loss_rate": 0.0, "packet_loss_count": 0, "rtt_min": 61.425, "rtt_avg": 99.731, "rtt_max": 212.597, "rtt_mdev": 27.566, "packet_duplicate_rate": 0.0, "packet_duplicate_count": 0 } ``` ``` -------------------------------- ### class PingParsing(timezone=None) Source: https://pingparsing.readthedocs.io/en/latest/pages/reference/parser.html Parser class to parsing ping command output. Accepts an optional timezone parameter for parsing timestamps and provides a parse method to parse ping command output. ```APIDOC ## PingParsing(timezone: Optional[tzinfo] = None) ### Description Parser class to parsing ping command output. ### Parameters - **timezone** (Optional[tzinfo]) - Optional - Time zone for parsing timestamps. ### Methods #### parse(ping_message: str | PingResult) -> PingStats Parse ping command output. Parameters: - **ping_message** (str or PingResult) - Required - `ping` command output. Returns: - **PingStats** - Parsed result. ``` -------------------------------- ### Execute pingparsing with --icmp-reply Source: https://pingparsing.readthedocs.io/en/latest/pages/usage/cli.html Use the --icmp-reply flag to include ICMP packet replies in the JSON output. The output includes icmp_replies with per-reply details like bytes, icmp_seq, ttl, time, and duplicate status. ```plaintext $ pingparsing google.com -c 3 --icmp-reply { "google.com": { "destination": "google.com", "packet_transmit": 3, "packet_receive": 3, "packet_loss_count": 0, "packet_loss_rate": 0.0, "rtt_min": 36.997, "rtt_avg": 49.1, "rtt_max": 60.288, "rtt_mdev": 9.533, "packet_duplicate_count": 0, "packet_duplicate_rate": 0.0, "icmp_replies": [ { "destination": "nrt20s21-in-f14.1e100.net (172.217.175.110)", "bytes": 64, "icmp_seq": 1, "ttl": 113, "time": 50.0, "duplicate": false }, { "destination": "nrt20s21-in-f14.1e100.net (172.217.175.110)", "bytes": 64, "icmp_seq": 2, "ttl": 113, "time": 60.2, "duplicate": false }, { "destination": "nrt20s21-in-f14.1e100.net (172.217.175.110)", "bytes": 64, "icmp_seq": 3, "ttl": 113, "time": 36.9, "duplicate": false } ] } } ``` -------------------------------- ### Parse ping command output with PingParsing Source: https://pingparsing.readthedocs.io/en/latest/pages/usage/library.html Parses a sample ping command output string using PingParsing.parse() and prints both the parsed statistics as JSON and each ICMP reply. The output shows the extracted statistics and the list of icmp_replies with fields like destination, bytes, timestamp, icmp_seq, ttl, time, and duplicate. ```python import json from textwrap import dedent import pingparsing parser = pingparsing.PingParsing() stats = parser.parse(dedent("""\ PING google.com (74.125.24.100) 56(84) bytes of data. [1524930937.003555] 64 bytes from 74.125.24.100: icmp_seq=1 ttl=39 time=148 ms [1524930937.787175] 64 bytes from 74.125.24.100: icmp_seq=2 ttl=39 time=137 ms [1524930938.787642] 64 bytes from 74.125.24.100: icmp_seq=3 ttl=39 time=137 ms [1524930939.787653] 64 bytes from 74.125.24.100: icmp_seq=4 ttl=39 time=136 ms [1524930940.788365] 64 bytes from 74.125.24.100: icmp_seq=5 ttl=39 time=136 ms --- google.com ping statistics --- 5 packets transmitted, 5 received, 0% packet loss, time 4001ms rtt min/avg/max/mdev = 136.537/139.174/148.006/4.425 ms """)) print("[extract ping statistics]") print(json.dumps(stats.as_dict(), indent=4)) print("\n[extract icmp replies]") for icmp_reply in stats.icmp_replies: print(icmp_reply) ``` ```text [ping statistics] { "destination": "google.com", "packet_transmit": 5, "packet_receive": 5, "packet_loss_count": 0, "packet_loss_rate": 0.0, "rtt_min": 136.537, "rtt_avg": 139.174, "rtt_max": 148.006, "rtt_mdev": 4.425, "packet_duplicate_count": 0, "packet_duplicate_rate": 0.0 } [icmp replies] {'destination': '74.125.24.100', 'bytes': 64, 'timestamp': datetime.datetime(2018, 4, 29, 0, 55, 37, 3555), 'icmp_seq': 1, 'ttl': 39, 'time': 148.0, 'duplicate': False} {'destination': '74.125.24.100', 'bytes': 64, 'timestamp': datetime.datetime(2018, 4, 29, 0, 55, 37, 787175), 'icmp_seq': 2, 'ttl': 39, 'time': 137.0, 'duplicate': False} {'destination': '74.125.24.100', 'bytes': 64, 'timestamp': datetime.datetime(2018, 4, 29, 0, 55, 38, 787642), 'icmp_seq': 3, 'ttl': 39, 'time': 137.0, 'duplicate': False} {'destination': '74.125.24.100', 'bytes': 64, 'timestamp': datetime.datetime(2018, 4, 29, 0, 55, 39, 787653), 'icmp_seq': 4, 'ttl': 39, 'time': 136.0, 'duplicate': False} {'destination': '74.125.24.100', 'bytes': 64, 'timestamp': datetime.datetime(2018, 4, 29, 0, 55, 40, 788365), 'icmp_seq': 5, 'ttl': 39, 'time': 136.0, 'duplicate': False} ``` -------------------------------- ### ParseError Source: https://pingparsing.readthedocs.io/en/latest/_modules/pingparsing/error.html Exception raised when failed to parse ping results. It includes an optional 'reason' property that can be set via the constructor's 'reason' keyword argument. ```APIDOC ## ParseError ### Description Exception raised when failed to parse ping results. ### Constructor `ParseError(*args, **kwargs)` ### Parameters - `*args` - Variable length argument list (passed to base Exception). - `**kwargs` - Keyword arguments. Supports `reason` (Optional[str]) - The reason for the parse error. ### Properties - `reason` (Optional[str]) - The reason for the parse error, or None if not set. ### Example python raise ParseError("Failed to parse", reason=ParseErrorReason.HEADER_NOT_FOUND) ``` -------------------------------- ### PingParsing.parse() Source: https://pingparsing.readthedocs.io/en/latest/pages/reference/index.html Parses ping command output and returns a PingStats object. ```APIDOC ## PingParsing.parse() ### Description Parses ping command output and returns a PingStats object. ### Method parse() ### Parameters None explicitly documented. ### Returns PingStats object containing parsed statistics. ``` -------------------------------- ### PingStats.as_tuple() Source: https://pingparsing.readthedocs.io/en/latest/pages/reference/index.html Returns the PingStats object as a tuple. ```APIDOC ## PingStats.as_tuple() ### Description Returns the PingStats object as a tuple. ### Method as_tuple() ### Parameters None. ### Returns Tuple representation of the PingStats object. ``` -------------------------------- ### Parse ping output from standard input Source: https://pingparsing.readthedocs.io/en/latest/pages/usage/cli.html Pipe ping output to pingparsing using '-' as the destination to parse from standard input. The output is a JSON object with ping statistics. ```bash $ ping -i 0.2 -w 20 192.168.2.101 | pingparsing - { "destination": "192.168.2.101", "packet_transmit": 99, "packet_receive": 88, "packet_loss_count": 11, "packet_loss_rate": 11.11111111111111, "rtt_min": 1.615, "rtt_avg": 26.581, "rtt_max": 93.989, "rtt_mdev": 19.886, "packet_duplicate_count": 0, "packet_duplicate_rate": 0.0 } ``` -------------------------------- ### PingStats.destination Source: https://pingparsing.readthedocs.io/en/latest/_modules/pingparsing/_stats.html Property that returns the ping destination as a string. ```APIDOC ## PingStats.destination ### Description Returns the ping destination. ### Returns - **destination** (str) - The ping destination. ``` -------------------------------- ### PingResult properties Source: https://pingparsing.readthedocs.io/en/latest/pages/reference/index.html Properties of PingResult: stdout, stderr, returncode. ```APIDOC ## PingResult properties ### Description Properties of PingResult: stdout, stderr, returncode. ### Properties - stdout: Standard output of the ping command. - stderr: Standard error of the ping command. - returncode: Return code of the ping command. ``` -------------------------------- ### PingTransmitter.ping() Source: https://pingparsing.readthedocs.io/en/latest/pages/reference/transmitter.html Sends ICMP packets using the configured parameters and returns a PingResult object containing the command execution output. ```APIDOC ## PingTransmitter.ping() ### Description Sends ICMP packets using the OS built-in `ping` command with the configured parameters. Returns a `PingResult` object containing the command execution result. ### Method `ping()` ### Parameters None (uses the attributes set on the `PingTransmitter` instance). ### Returns - **PingResult** - The `ping` command execution result. ### Raises - **ValueError** - If parameters are not valid. ### Example ```python from pingparsing import PingTransmitter transmitter = PingTransmitter() transmitter.destination = "example.com" transmitter.count = 4 result = transmitter.ping() ``` ``` -------------------------------- ### PingStats.as_tuple() Source: https://pingparsing.readthedocs.io/en/latest/_modules/pingparsing/_stats.html Converts the ping statistics into a namedtuple. The namedtuple fields correspond to the keys of the dictionary returned by as_dict(). ```APIDOC ## as_tuple() ### Description Converts the ping statistics into a namedtuple. The namedtuple fields correspond to the keys of the dictionary returned by as_dict(). ### Method as_tuple() ### Returns - **namedtuple** - A namedtuple containing the ping statistics with fields: destination, packet_transmit, packet_receive, packet_loss_rate, packet_loss_count, rtt_min, rtt_avg, rtt_max, rtt_mdev, packet_duplicate_rate, packet_duplicate_count. ### Example ```python >>> import pingparsing >>> parser = pingparsing.PingParsing() >>> parser.parse(ping_result) >>> parser.as_tuple() PingResult(destination='google.com', packet_transmit=60, packet_receive=60, packet_loss_rate=0.0, packet_loss_count=0, rtt_min=61.425, rtt_avg=99.731, rtt_max=212.597, rtt_mdev=27.566, packet_duplicate_rate=0.0, packet_duplicate_count=0) ``` ``` -------------------------------- ### PingStats.is_empty() Source: https://pingparsing.readthedocs.io/en/latest/pages/reference/index.html Checks if the PingStats object is empty. ```APIDOC ## PingStats.is_empty() ### Description Checks if the PingStats object is empty. ### Method is_empty() ### Parameters None. ### Returns Boolean indicating whether the stats are empty. ``` -------------------------------- ### Print ICMP packet replies with pingparsing --icmp-reply Source: https://pingparsing.readthedocs.io/en/latest/pages/usage/cli.html Uses the --icmp-reply flag to include detailed ICMP reply information in the output. The JSON output for each file includes an icmp_replies array with per-reply fields like icmp_seq, ttl, time, and duplicate status. ```bash $ pingparsing ping.txt osx.txt --icmp-reply { "ping.txt": { "destination": "google.com", "packet_transmit": 60, "packet_receive": 60, "packet_loss_count": 0, "packet_loss_rate": 0.0, "rtt_min": 61.425, "rtt_avg": 99.731, "rtt_max": 212.597, "rtt_mdev": 27.566, "packet_duplicate_count": 0, "packet_duplicate_rate": 0.0, "icmp_replies": [] }, "osx.txt": { "destination": "google.com", "packet_transmit": 5, "packet_receive": 5, "packet_loss_count": 0, "packet_loss_rate": 0.0, "rtt_min": 20.482, "rtt_avg": 31.927, "rtt_max": 46.093, "rtt_mdev": 8.292, "packet_duplicate_count": 0, "packet_duplicate_rate": 0.0, "icmp_replies": [ { "icmp_seq": 0, "ttl": 53, "time": 20.482, "duplicate": false }, { "icmp_seq": 1, "ttl": 53, "time": 32.55, "duplicate": false }, { "icmp_seq": 2, "ttl": 53, "time": 32.013, "duplicate": false }, { "icmp_seq": 3, "ttl": 53, "time": 28.498, "duplicate": false }, { "icmp_seq": 4, "ttl": 53, "time": 46.093, "duplicate": false } ] } } ``` -------------------------------- ### ParseError and ParseErrorReason Source: https://pingparsing.readthedocs.io/en/latest/pages/reference/index.html Error classes for parsing ping output. ParseErrorReason includes HEADER_NOT_FOUND and EMPTY_STATISTICS. ```APIDOC ## ParseError and ParseErrorReason ### Description Error classes for parsing ping output. ParseErrorReason includes HEADER_NOT_FOUND and EMPTY_STATISTICS. ### Errors - ParseError: Exception raised when parsing fails. - ParseErrorReason: Enum of possible reasons. - HEADER_NOT_FOUND: Header not found in ping output. - EMPTY_STATISTICS: Statistics section is empty. ``` -------------------------------- ### PingTransmitter.ping() Source: https://pingparsing.readthedocs.io/en/latest/_modules/pingparsing/_pingtransmitter.html Sends ICMP packets to the configured destination and returns the execution result. Raises ValueError if parameters are invalid. ```APIDOC ## PingTransmitter.ping() ### Description Sends ICMP packets to the configured destination and returns the execution result. Raises ValueError if parameters are invalid. ### Method ping() ### Parameters None ### Returns - **PingResult** - The ping command execution result. ### Raises - **ValueError** - If parameters are not valid. ### Example python from pingparsing import PingTransmitter transmitter = PingTransmitter() transmitter.destination = "127.0.0.1" result = transmitter.ping() ``` -------------------------------- ### ParseError Source: https://pingparsing.readthedocs.io/en/latest/pages/reference/error.html Exception raised when failed to parse ping results. It inherits from the built-in Exception class. ```APIDOC ## ParseError ### Description Exception raised when failed to parse ping results. ### Base Class Exception ### Constructor ParseError(*args, **kwargs) ### Usage Raised internally by pingparsing when parsing ping output fails. ``` -------------------------------- ### PingStats.icmp_replies Source: https://pingparsing.readthedocs.io/en/latest/_modules/pingparsing/_stats.html Property that returns ICMP packet reply information. ```APIDOC ## PingStats.icmp_replies ### Description Returns ICMP packet reply information. ### Returns - **icmp_replies** (list of dict) - ICMP packet reply information. Note: time<1ms considered as time=1. ``` -------------------------------- ### PingStats.as_dict() Source: https://pingparsing.readthedocs.io/en/latest/pages/reference/index.html Returns the PingStats object as a dictionary. ```APIDOC ## PingStats.as_dict() ### Description Returns the PingStats object as a dictionary. ### Method as_dict() ### Parameters None. ### Returns Dictionary representation of the PingStats object. ``` -------------------------------- ### Validate IPv6 link-local interface Source: https://pingparsing.readthedocs.io/en/latest/_modules/pingparsing/_pingtransmitter.html Validates that an interface is provided when pinging an IPv6 link-local address. ```python def __validate_interface(self) -> None: if not self.__is_ipv6(): return if not ipaddress.ip_network(str(self.destination)).is_link_local: return if typepy.is_null_string(self.interface): raise ValueError("interface required to ping to IPv6 link local address") ``` -------------------------------- ### PingTransmitter attributes Source: https://pingparsing.readthedocs.io/en/latest/pages/reference/transmitter.html Configuration attributes for the PingTransmitter class that control the behavior of the ping command. ```APIDOC ## PingTransmitter attributes ### Description Attributes that configure the ping command execution. ### Attributes - **count** (int | None) - Number of sending ICMP packets. Ignored if `None`. Defaults to `None`. - **packet_size** (int | None) - Specifies the number of data bytes to be sent. Defaults to `None`. - **ttl** (int | None) - Specifies the Time to Live. Defaults to `None`. - **ping_option** (str | Sequence[str]) - Additional `ping` command option. Defaults to `""`. - **interface** (str | None) - Interface name or zone-id. Required when `destination` is IPv6 link-local scope address. Defaults to `None`. - **timestamp** (bool) - [Only for Linux environment] If `True`, add a timestamp for each ping result. Defaults to `False`. - **auto_codepage** (bool) - [Only for Windows environment] Automatically change the code page if `True`. Defaults to `True`. - **deadline** (property) - Timeout before ping exits. Can be a number or string (e.g., `"1sec"`). If only a number is specified, unit is considered seconds. Defaults to `None`. If both `deadline` and `count` are `None`, `deadline` is automatically set to `3 seconds`. - **destination** (property) - Hostname or IP address (IPv4/IPv6) to send ICMP packets. - **destination_host** (property) - Alias to `destination`. - **timeout** (property) - Time to wait for a response per packet. Can be a number or string (e.g., `"1sec"`). If only a number is specified, unit is considered seconds. Defaults to `None`. Use system default timeout if `None`. ### Example ```python from pingparsing import PingTransmitter transmitter = PingTransmitter() transmitter.destination = "192.0.2.1" transmitter.count = 3 transmitter.packet_size = 64 transmitter.ttl = 64 transmitter.deadline = "5sec" transmitter.timeout = "1sec" ``` ``` -------------------------------- ### PingTransmitter properties Source: https://pingparsing.readthedocs.io/en/latest/pages/reference/index.html Properties of PingTransmitter: count, packet_size, ttl, ping_option, interface, timestamp, auto_codepage, deadline, destination, destination_host, timeout. ```APIDOC ## PingTransmitter properties ### Description Properties of PingTransmitter: count, packet_size, ttl, ping_option, interface, timestamp, auto_codepage, deadline, destination, destination_host, timeout. ### Properties - count: Number of ping packets to send. - packet_size: Size of the ping packet. - ttl: Time to live. - ping_option: Additional ping options. - interface: Network interface to use. - timestamp: Timestamp for the ping. - auto_codepage: Whether to auto-detect codepage. - deadline: Deadline for the ping. - destination: Destination address. - destination_host: Destination hostname. - timeout: Timeout for the ping. ``` -------------------------------- ### PingStats.rtt_min Source: https://pingparsing.readthedocs.io/en/latest/_modules/pingparsing/_stats.html Property that returns the minimum round trip time of transmitted ICMP packets. ```APIDOC ## PingStats.rtt_min ### Description Returns the minimum round trip time of transmitted ICMP packets. ### Returns - **rtt_min** (float) - Minimum round trip time in milliseconds. ``` -------------------------------- ### PingStats properties Source: https://pingparsing.readthedocs.io/en/latest/pages/reference/index.html Properties of PingStats: destination, icmp_replies, packet_duplicate_count, packet_duplicate_rate, packet_loss_count, packet_loss_rate, packet_receive, packet_transmit, rtt_avg, rtt_max, rtt_mdev, rtt_min. ```APIDOC ## PingStats properties ### Description Properties of PingStats: destination, icmp_replies, packet_duplicate_count, packet_duplicate_rate, packet_loss_count, packet_loss_rate, packet_receive, packet_transmit, rtt_avg, rtt_max, rtt_mdev, rtt_min. ### Properties - destination: Destination address. - icmp_replies: Number of ICMP replies. - packet_duplicate_count: Number of duplicate packets. - packet_duplicate_rate: Rate of duplicate packets. - packet_loss_count: Number of lost packets. - packet_loss_rate: Rate of lost packets. - packet_receive: Number of packets received. - packet_transmit: Number of packets transmitted. - rtt_avg: Average round-trip time. - rtt_max: Maximum round-trip time. - rtt_mdev: Mean deviation of round-trip time. - rtt_min: Minimum round-trip time. ``` -------------------------------- ### PingStats Class Definition Source: https://pingparsing.readthedocs.io/en/latest/_modules/pingparsing/_stats.html The PingStats class stores and provides access to ping result statistics including destination, packet counts, RTT values, and ICMP replies. ```python """ .. codeauthor:: Tsuyoshi Hombashi """ from typing import Dict, Optional, Tuple, Union, cast from ._typing import IcmpReplies [docs] class PingStats: def __init__(self, *args, **kwargs) -> None: self.__destination = kwargs.pop("destination", None) self.__packet_transmit = kwargs.pop("packet_transmit", None) self.__packet_receive = kwargs.pop("packet_receive", None) self.__rtt_min = kwargs.pop("rtt_min", None) self.__rtt_avg = kwargs.pop("rtt_avg", None) self.__rtt_max = kwargs.pop("rtt_max", None) self.__rtt_mdev = kwargs.pop("rtt_mdev", None) self.__duplicates = kwargs.pop("duplicates", None) self.__icmp_replies = kwargs.pop("icmp_replies", []) @property def destination(self) -> str: """ The ping destination. Returns: |str|: """ return self.__destination @property def packet_transmit(self) -> Optional[int]: """ Number of packets transmitted. Returns: |int|: """ return self.__packet_transmit @property def packet_receive(self) -> Optional[int]: """ Number of packets received. Returns: |int|: """ return self.__packet_receive @property def packet_loss_count(self) -> Optional[int]: """ Number of packet losses. Returns: |int|: |None| if the value is not a number. """ try: return cast(int, self.packet_transmit) - cast(int, self.packet_receive) except TypeError: return None @property def packet_loss_rate(self) -> Optional[float]: """ Percentage of packet loss |percent_unit|. Returns: |float|: |None| if the value is not a number. """ try: return (cast(int, self.packet_loss_count) / cast(int, self.packet_transmit)) * 100 except (TypeError, ZeroDivisionError, OverflowError): return None @property def rtt_min(self) -> Optional[float]: """ Minimum round trip time of transmitted ICMP packets |msec_unit|. Returns: |float|: """ return self.__rtt_min @property def rtt_avg(self) -> Optional[float]: """ Average round trip time of transmitted ICMP packets |msec_unit|. Returns: |float|: """ return self.__rtt_avg @property def rtt_max(self) -> Optional[float]: """ Maximum round trip time of transmitted ICMP packets |msec_unit|. Returns: |float|: """ return self.__rtt_max @property def rtt_mdev(self) -> Optional[float]: """ Standard deviation of transmitted ICMP packets. Returns: |float|: |None| when parsing Windows ping result. """ return self.__rtt_mdev @property def packet_duplicate_count(self) -> Optional[int]: """ Number of duplicated packets. Returns: |int|: |None| when parsing Windows ping result. """ return self.__duplicates @property def packet_duplicate_rate(self) -> Optional[float]: """ Percentage of duplicated packets |percent_unit|. Returns: |float|: |None| if the value is not a number. """ try: return (cast(int, self.packet_duplicate_count) / cast(int, self.packet_receive)) * 100 except (TypeError, ZeroDivisionError, OverflowError): return None @property def icmp_replies(self) -> IcmpReplies: """ ICMP packet reply information. .. note: ``time<1ms`` considered as ``time=1`` Returns: |list| of |dict|: """ return self.__icmp_replies [docs] def is_empty(self): return all( [ self.destination is None, self.packet_transmit is None, self.packet_receive is None, self.packet_loss_count is None, self.packet_loss_rate is None, self.packet_duplicate_count is None, self.packet_duplicate_rate is None, self.rtt_min is None, self.rtt_avg is None, self.rtt_max is None, self.rtt_mdev is None, not self.icmp_replies, ] ) [docs] def as_dict( self, include_icmp_replies: bool = False ) -> Dict[str, Union[str, int, float, IcmpReplies, None]]: """ ping statistics. Returns: |dict|: ```