Skip to content

Instantly share code, notes, and snippets.

@ivyleavedtoadflax
Forked from dansimau/ping-csv.sh
Created February 22, 2018 15:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ivyleavedtoadflax/86fe3879710abd896e93b83f0b1f78a3 to your computer and use it in GitHub Desktop.
Save ivyleavedtoadflax/86fe3879710abd896e93b83f0b1f78a3 to your computer and use it in GitHub Desktop.
Ping a host and output each reply in CSV format
#!/bin/bash
#
# Do a ping and output results as CSV.
#
# dsimmons@squiz.co.uk
# 2011-12-23
#
if [ $# -lt 1 ]; then
echo "Usage: $0 [--add-timestamp] <ping host>"
exit 99
fi
opts=""
for opt in $*; do
if [ "$opt" == "--add-timestamp" ]; then
opts="$opts $opt"
shift
fi
done
trap echo 0
ping -c 10 $* | while read line; do
# Skip header
[[ "$line" =~ ^PING ]] && continue
# Skip non-positive responses
[[ ! "$line" =~ "bytes from" ]] && continue
# Extract address field
addr=${line##*bytes from }
addr=${addr%%:*}
# Extract IP address
if [[ "$addr" =~ (\(|\)) ]]; then
ip=${addr##*(}
ip=${ip%%)*}
else
ip=$addr
fi
# Extract seq
seq=${line##*icmp_seq=}
seq=${seq%% *}
# Extract time
time=${line##*time=}
time=${time%% *}
echo -n "$ip,$seq,$time"
# Calculate date (not totally accurate)
if [[ "$opts" =~ "--add-timestamp" ]]; then
timestamp=$(date +%s)
echo -n ",$timestamp"
fi
echo
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment