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
andipconfig /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:
This works because of the return code of
ping
, as detailed in the man page: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 asroot
. For default Ubuntu, you can add a cron job using:To have this check run every hour, for example:
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.