I run a Raspberry Pi VPN router. I want it to reboot automatically when it looses the WAN connection, as it does from time to time.

There are a few ways to do this - this is a simple way. Thank you We Work We Play.

I adapted the WWWP script:

  • changed the script name to reflect my use,
  • run by root crontab,
  • ping an interweb website with a single ping,
  • write a message to /var/log/messages if reboot.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
#! /bin/bash
# Checks for WAN connection using ping
# if ping fails with non-zero exit code then
#  reboot
#
ping -c 1 neilt.org > /dev/null
if [ $? != 0 ] 
then
    logger WAN probably down so rebooting
    /sbin/shutdown --r now
fi
exit

I put it in:

/usr/local/bin/checkwan.sh

Use sudo if necessary to access /usr/local/bin/.

Set permissions:

sudo chmod 775 /usr/local/bin/checkwan.sh

Ran crontab and added a entry to run checkwan.sh every 5 minutes:

sudo crontab -e

I used sudo crontab -e If we omit sudo then it may not work.

crontab entry:

*/5 * * * * /usr/local/bin/checkwan.sh >> /dev/null 2>&1

Check that this works by disconnecting or switching off the WAN to trigger a reboot.

sudo grep WAN /var/log/messages

Or

sudo grep WAN /var/log/syslog

Shows us the log entry for each time that the script commands a reboot.