automatic network reboot

Published on 22 Mar 2018

Weeks ago I noticed something strange that happened quite frequently to my Xubuntu 17.10 virtual machine (Windows 10 host). After a few hours (sometimes could be minutes), I lost my network connection and I had to restart the network connection manually with systemctl.

sudo systemctl restart NetworkManager

I tried turning off the Windows power saver option & disabled the power-saving feature for the network hardware adapter, but I still faced the problem. Then today I thought to myself if I could not prevent this from happening, let’s automate the recovery.

I copied a script from here and modified it a little bit.

#!/bin/bash

# The IP for the server you wish to ping (8.8.8.8 is a public Google DNS server)
SERVER=8.8.8.8

# Only send two pings, sending output to /dev/null
ping -c2 ${SERVER} > /dev/null

# If the return code from ping ($?) is not 0 (meaning there was an error)
if [ $? != 0 ]
then
    # Restart the network interface, assuming NetworkManager is the right daemon
    sudo systemctl restart NetworkManager
fi

This script only works if Google Public DNS 8.8.8.8 will never go down. This script was saved as netreboot.sh in the folder /usr/local/bin and made executable with chmod +x command.

To run this automatically, I used crontab.

Open crontab with this command:

# Make it executable
sudo chmod +x /usr/local/bin/netreboot.sh

# Open crontab
/etc/crontab

# Place this line
*/1 * * * * root  /usr/local/bin/netreboot.sh

The syntax */1 means crontab will attempt at running this script every 1 minute.

It worked for me and I felt slightly relieved.

There’s one more thing though. When networking gets restarted, the local IP address could change. Here’s what I did:

static IP Assign static IP.

Done!