#!/bin/bash
# getstats - Every 'n' minutes, grabs netstats values (via crontab).

logfile="/Users/taylor/.netstatlog"   # change for your configuration
temp="/tmp/getstats.$$.tmp"

trap "`which rm` -f $temp" 0

if [ ! -e $logfile ] ; then     # first time run?
  touch $logfile
fi
( netstat -s -p tcp > $temp

# Check your log file the first time this is run: some versions of netstat 
# report more than one line, which is why the “| head -1” is used here.
sent="$(grep 'packets sent' $temp | cut -d\  -f1 | sed 
's/[^[:digit:]]//g' | head -1)"
resent="$(grep 'retransmitted' $temp | cut -d\  -f1 | sed 's/[^[:digit:]]//g')"
received="$(grep 'packets received$' $temp | cut -d\  -f1 | \
  sed 's/[^[:digit:]]//g')"
dupacks="$(grep 'duplicate acks' $temp | cut -d\  -f1 | \
  sed 's/[^[:digit:]]//g')"
outoforder="$(grep 'out-of-order packets' $temp | cut -d\  -f1 | \
  sed 's/[^[:digit:]]//g')"
connectreq="$(grep 'connection requests' $temp | cut -d\  -f1 | \
  sed 's/[^[:digit:]]//g')"
connectacc="$(grep 'connection accepts' $temp | cut -d\  -f1 | \
  sed 's/[^[:digit:]]//g')"
retmout="$(grep 'retransmit timeouts' $temp | cut -d\  -f1 | \
  sed 's/[^[:digit:]]//g')"

/bin/echo -n "time=$(date +%s);"
/bin/echo -n "snt=$sent;re=$resent;rec=$received;dup=$dupacks;"
/bin/echo -n "oo=$outoforder;creq=$connectreq;cacc=$connectacc;"
echo "reto=$retmout"

) >> $logfile

exit 0
