Skip to content

Commit

Permalink
add support of duplicates
Browse files Browse the repository at this point in the history
  • Loading branch information
shell-autonomic-sh committed Jul 2, 2019
1 parent d88a969 commit 7a6ed8f
Showing 1 changed file with 11 additions and 3 deletions.
14 changes: 11 additions & 3 deletions pingparser.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,9 @@

# This one works on OS X output which includes the percentage in 0.0% format
# https://regex101.com/r/nmjQzI/2
rslt_matcher = re.compile(r'(\d+) packets transmitted, (\d+) (?:packets )?received, (\d+\.?\d*)% packet loss')
rslt_matcher = re.compile(r'(\d+) packets transmitted, (\d+) (?:packets )?received')
dups_matcher = re.compile(r'\+(\d) duplicates')
loss_matcher = re.compile(r'(\d+\.?\d*)% packet loss')

# Pull out round-trip min/avg/max/stddev = 49.042/49.042/49.042/0.000 ms
minmax_matcher = re.compile(r'(\d+.\d+)/(\d+.\d+)/(\d+.\d+)/(\d+.\d+)')
Expand All @@ -36,6 +38,7 @@
format_replacements = [('%h', 'host'),
('%s', 'sent'),
('%r', 'received'),
('%d', 'duplicates'),
('%p', 'packet_loss'),
('%m', 'minping'),
('%a', 'avgping'),
Expand All @@ -46,12 +49,14 @@
default_format = ','.join([fmt for fmt, field in format_replacements])


def _get_match_groups(ping_output, regex):
def _get_match_groups(ping_output, regex, default=None):
"""
Get groups by matching regex in output from ping command.
"""
match = regex.search(ping_output)
if not match:
if default is not None:
return default
raise Exception('Invalid PING output:\n' + ping_output)
return match.groups()

Expand All @@ -74,7 +79,9 @@ def parse(ping_output):
in milliseconds
"""
host = _get_match_groups(ping_output, host_matcher)[0]
sent, received, packet_loss = _get_match_groups(ping_output, rslt_matcher)
sent, received = _get_match_groups(ping_output, rslt_matcher)
duplicates, = _get_match_groups(ping_output, dups_matcher, default=('0',))
packet_loss, = _get_match_groups(ping_output, loss_matcher)

try:
minping, avgping, maxping, jitter = _get_match_groups(ping_output,
Expand All @@ -85,6 +92,7 @@ def parse(ping_output):
return {'host' : host,
'sent' : sent,
'received' : received,
'duplicates' : duplicates,
'packet_loss' : packet_loss,
'minping' : minping,
'avgping' : avgping,
Expand Down

0 comments on commit 7a6ed8f

Please sign in to comment.