Skip to content

Instantly share code, notes, and snippets.

@jez500
Last active May 10, 2023 11:42
Show Gist options
  • Save jez500/7adc888a7bf52dbfd5ea5fdf0a449293 to your computer and use it in GitHub Desktop.
Save jez500/7adc888a7bf52dbfd5ea5fdf0a449293 to your computer and use it in GitHub Desktop.
Check for internet on router or router host (eg proxmox) and reboot if cannot ping hosts
#!/bin/sh
#=====================================================================
# pingtest.sh
# -----------
# Inspiration: https://forum.netgate.com/topic/64563/pfsense-auto-reboot-script-when-google-is-unreachable/9
#
# Prep
# mkdir -p /var/log/pingtest
#
# Setup logrotate
# Create /etc/logrotate.d/pingtest.conf with contents:
# /var/log/pingtest/* {
# weekly
# rotate 3
# size 1M
# compress
# delaycompress
# }
#
# Add Cron (every 5 mins)
# */5 * * * * /root/pingtest.sh >/dev/null 2>&1
#=====================================================================
#=====================================================================
# USER SETTINGS
# Hosts to check
ALLDEST="google.com yahoo.com"
# Wait beetween failures
SLEEP_ON_FAIL=5
# Max failures
MAX_FAILS=2
# Uptime before kicking in
UPTIME_MINS=30
# Log file
LOGFILE=/var/log/pingtest/ping.log
#=====================================================================
# Abort if uptime less than 30 mins to avoid reboot loops
uptime=`awk '{print int($1/60)}' /proc/uptime`
if [ $uptime -le $UPTIME_MINS ]; then
echo "Skipping pingtest until up for $UPTIME_MINS mins (current uptime $uptime mins)" >> $LOGFILE
exit 0
fi
# Log when script ran.
echo "==== Pingtest - Time:" `date +%Y%m%d.%H%M%S` "- Uptime: $uptime mins ====" >> $LOGFILE
COUNT=1
while [ $COUNT -le $MAX_FAILS ]
do
for DEST in $ALLDEST
do
echo "Pinging $DEST" >> $LOGFILE
ping -c1 $DEST >/dev/null 2>/dev/null
if [ $? -eq 0 ]
then
echo "Ping $DEST OK." >> $LOGFILE
exit 0
fi
done
echo "All pings Failed $COUNT times" >> $LOGFILE
if [ $COUNT -ge $MAX_FAILS ]
then
echo `date +%Y%m%d.%H%M%S` "Max failures of $MAX_FAILS reached. Rebooting..." >> $LOGFILE
/usr/sbin/shutdown -r now >> $LOGFILE
exit 1
else
echo "Waiting $SLEEP_ON_FAIL seconds until next ping attempt" >> $LOGFILE
sleep "$SLEEP_ON_FAIL"
fi
COUNT=`expr $COUNT + 1`
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment