Daniel Brookes Daniel Brookes - 1 year ago 116
Linux Question

Using bash to automatically restart Raspberry PI interfaces when net goes down

I have a Raspberry PI which is used as a clocking in machine.

The ethernet interface goes down every couple of hours to every couple of days.

This is the second pi we have set up as a clocking in machine. On the original one, it use wireless and the same problem happened on the wireless interface. With the wifi issue, you could unplug the usb wifi adapter and plug it back in to sort it. However, i do not have access to the ethernet slot, and i can not open the pi case up on the new pi.

The plan is to use the script with cron to run every 10 minutes or so.

Because of this, i resorted to restarting the interface with a script. The idea of the script is to ping the gateway. If no response is recieved, then the pi should run IFDOWN and then IFUP on the interface eth0. If this fails, it should reboot. However, every script i have tried has failed. Currently i am using the following script:

function pingf1 {
ping1=$(ping -c 1
echo $ping1result
if [ $ping1result -eq 1 ]
sudo /sbin/ifdown eth0 #or wlan0 if using on old clocker
sudo /sbin/ifup eth0 #or wlan0 if using on old clocker

I am aware that this post will probably be marked as a duplicate post, but i have tried a lot of different solutions on stack exchange already, and none have worked for me.

Thanks in advance for any assistance.

Answer Source

Sounds like @andlrc is correct with regards to sudo but if you created the cronjob from the root user then you don't need sudo in there.

To keep things simple, use this script in your cronjob instead:

if ! ping -q -c 1 &>/dev/null; then
  /sbin/ifdown eth0 #or wlan0 if using on old clocker
  /sbin/ifup eth0 #or wlan0 if using on old clocker

Here we are not using unnecessary variables and checks on $? since it can be done in an if statement.

Make sure your cronjob is run through root so you don't have to include sudo since by default it ask for a password unless you specify in /etc/sudoers

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download