Skip to content

Instantly share code, notes, and snippets.

@joshlarsen
Created June 16, 2020 15:46
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 joshlarsen/29320010b95540b68935f1b648d62a83 to your computer and use it in GitHub Desktop.
Save joshlarsen/29320010b95540b68935f1b648d62a83 to your computer and use it in GitHub Desktop.
Monitor IPS uptime by pinging an external IP
#!/bin/bash
#
# Ping external IP from wired network to monitor for ISP outtage
# 2020-06-16
#
# runs on pi-hole from cron every day
#
# kill any other instances running
# name log file day_of_month_down.txt
# remove todays log file if there is one, since it will be a month old
#
# run `ping -c 1 -t 2 8.8.8.8` in a loop, check exit code, if > 0, append log file with "2020-06-16 12:34:56 down" then sleep 1
OS=$(uname)
SCRIPT=$(basename "$0")
DAY_OF_MONTH=$(date +%d)
LOG_FILE="${DAY_OF_MONTH}_down.txt"
EXTERNAL_IP="8.8.8.8"
# EXTERNAL_IP="10.10.10.10"
TIMEOUT_FLAG="-W"
# ping uses a different flag for timeout on macOS
if [ "${OS}" == "Darwin" ]
then
TIMEOUT_FLAG="-t"
fi
# kill any other instances that are at least 1 second old
if [ "${OS}" == "Linux" ]
then
KILL=$(killall -q -o 1s ${SCRIPT})
fi
# clean up old log file
CLEANUP=$(rm -f ${LOG_FILE})
# run until day changes
# script will get killed by next day's script anyway
while [ "$DAY_OF_MONTH" == "$(date +%d)" ]
do
# ping quiet mode, one time, for a max of one second
CMD="ping -q -c 1 ${TIMEOUT_FLAG} 1 ${EXTERNAL_IP}"
# run the command
$CMD
# exit status
STATUS=$?
# internet is probably down if we can't ping out
if [ "$STATUS" -gt "0" ]
then
TIMESTAMP=$(date "+%Y-%m-%d %H:%M:%S")
LOG=$(echo "${TIMESTAMP} down" >> ${LOG_FILE})
fi
sleep 1
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment