# Ubuntu – automatically reboot if disconnected from the internet

rebootscriptUbuntu

I have an old desktop that I'm running as a web server from my home while I'm at college. The internet at home is crappy and a lot of times when it goes down, the desktop can't reconnect without a reboot.

Is there a way to make a script that loads on startup and every 12 hours or so, will attempt to ping the router, and if it fails, reboots the server?

EDIT:
Ok, I was able to make this script after googling around a bit.

#!/bin/bash

ping -c 1 192.168.1.1 > /dev/null
if [ $? -ne 0 ]; then reboot fi  That tests if the ping is successful, and if it's not it reboots. Now what do I need to do to make this run on a set schedule? #### Best Answer You didn't mention the operating system, but if you're using Windows, something like this may be helpful: JScript for Ping, Renew IP and Network Info / Repair. This is a script I put together for a similar issue. It does pretty much exactly what you're looking for, in that it pings the default gateway (which will be your router) on a given schedule, and then takes required action if the ping fails. In this case, the problem PCs didn't need to be rebooted, but simply have an ipconfig /release and ipconfig /renew scripted in order to regain connectivity. Something like this might work well for your case as well. If a full reboot is still required, this script could be easily modified to account for that as well. For Linux, you could use a shell script like this: #!/bin/sh ping -c5 192.168.1.1 if [$? -eq 0 ]; then
echo "ok"
else
reboot
fi


This works because of the return code of ping, as detailed in the man page:

If ping does not receive any reply packets at all it will exit with code 1. If a packet count and deadline are both specified, and fewer than count packets are received by the time the deadline has arrived, it will also exit with code 1. On other error it exits with code 2. Otherwise it exits with code 0. This makes it possible to use the exit code to see if a host is alive or not.

After replacing 192.168.1.1 with the address of your router, you could schedule this to run every hour or so using cron. In order to reboot, you'll need to run this as root. For default Ubuntu, you can add a cron job using:

sudo crontab -e


To have this check run every hour, for example:

00 * * * * /path/to/script/pingRouterCheckReboot.sh


You'll need to ensure that the script is executable (chmod +x).

If you find that bringing the interface down and back up is sufficient, you could do this instead, doing something like ifdown eth0; ifup eth0. Or, combine approaches: First do this, and then do the ping test again. If connectivity still isn't restored, then force the drastic measure of a full reboot.