Skip to content

Instantly share code, notes, and snippets.

@dansimau
Created December 23, 2011 11:01
Show Gist options
  • Star 16 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save dansimau/1513880 to your computer and use it in GitHub Desktop.
Save dansimau/1513880 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 $* | 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
@dansimau
Copy link
Author

Example output:

$ ./ping-csv.sh google.com
209.85.229.105,0,7.629
209.85.229.105,1,7.551
209.85.229.105,2,7.409
^C
$ ./ping-csv.sh --add-timestamp google.com
209.85.229.105,0,7.544,1325068107
209.85.229.105,1,7.681,1325068108
209.85.229.105,2,7.645,1325068109
209.85.229.105,3,7.827,1325068110
209.85.229.105,4,7.696,1325068111
209.85.229.105,5,7.570,1325068112
^C
$ 

Write to a file whilst also showing output:

$ ./ping-csv.sh --add-timestamp google.com |tee output.csv
209.85.229.105,0,7.591,1325068169
209.85.229.105,1,7.527,1325068170
209.85.229.105,2,7.588,1325068171
209.85.229.105,3,7.462,1325068172
209.85.229.105,4,7.428,1325068173
...

etc.

@ishyherts
Copy link

Hi, thank you for the script on exporting the ping output to csv, is there a way I can add some code to that so the ping runs for a specific time period or a number of packets? Thank you.

@willsthompson
Copy link

FYI, to make this output correctly in OSX, change every echo -n (lines 52 and 57) to printf.

@bbbenji
Copy link

bbbenji commented May 22, 2020

@ishyherts, add ((c++)) && ((c==10)) && break to line 53.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment