Last active
October 28, 2017 18:38
-
-
Save benton/03f27c4b444819660f5a6d99ada411aa to your computer and use it in GitHub Desktop.
Ping an IP forever and report its reachability
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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