Skip to content

Instantly share code, notes, and snippets.

@benton
Last active October 28, 2017 18:38
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 benton/03f27c4b444819660f5a6d99ada411aa to your computer and use it in GitHub Desktop.
Save benton/03f27c4b444819660f5a6d99ada411aa to your computer and use it in GitHub Desktop.
Ping an IP forever and report its reachability
#!/usr/bin/env bash
# pings an IP address forever and tracks whether it is accessible
# logs the connection's state change to $STDOUT
ip='8.8.8.8'
track_attempts=5
failure_threshold=3
delay=1
# track state
state='up'
failures=0
echo "Pinging ${ip} forever (CTRL-C / SIGTERM to quit)..."
while true ; do
if ping -c 1 $ip >/dev/null 2>&1 ; then
# ping succeeded
if [ "$failures" -gt "0" ] ; then let failures-=1 ; fi
else # ping failed
if [ "$failures" -lt "$track_attempts" ] ; then let failures+=1 ; fi
fi
# echo "Failures in the last $track_attempts attempts: $failures"
# detect state change...
if [ "$failures" -gt "$failure_threshold" ] ; then
if [ "$state" == 'up' ] ; then
echo "Connection has gone down at $(date +'%Y-%m-%d %H:%M:%S %Z')!"
state='down'
fi
else
if [ "$state" == 'down' ] ; then
echo "Connection has come up at $(date +'%Y-%m-%d %H:%M:%S %Z')!"
state='up'
fi
fi
sleep $delay
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment