Auto Check Connection and Restart Network Manager if Down

Introduction

In this article, we will create a simple script and a cron job to automatically check the connection status of your wireless network (Wi-Fi) and restart the Network Manager service if the connection is down. This can be particularly useful to ensure that your network remains stable and connected, especially in situations where the Wi-Fi connection tends to drop or become unreliable.

Prerequisites

Before you begin, ensure that you have:

  • Root Access: You need root or sudo access to create and modify system files and services.

Step 1: Create a Cron Job

First, let’s create a cron job that will periodically run the connection check script.

1
sudo vim /etc/cron.d/checkconnection

Add the following line to the file:

1
* * * * * root /usr/sbin/checkconnection

This line schedules the checkconnection script to run every minute. You can adjust the timing according to your preference by modifying the * * * * * part. The format is minute hour day month day-of-week.

Save the file and exit your text editor.

Step 2: Create the Connection Check Script

Now, let’s create the checkconnection script.

1
sudo vim /usr/sbin/checkconnection

Add the following content to the script:

1
2
3
4
5
6
7
#!/bin/bash

if /sbin/iwconfig wlan0 | grep -o "Access Point: Not-Associated"
then
    sudo service network-manager restart
    echo "Network Manager Restarted!"
fi

Here’s what this script does:

  • It checks the status of the wireless network interface (wlan0) using iwconfig.
  • If the “Access Point: Not-Associated” message is found (indicating that the Wi-Fi is not connected to an access point), it restarts the Network Manager service.
  • It also prints a message to the console to indicate that Network Manager has been restarted.

Save the file and exit your text editor.

Step 3: Make the Script Executable

Before the script can be executed, make it executable using the following command:

1
sudo chmod +x /usr/sbin/checkconnection

This command grants execute permission to the script.

Conclusion

With the cron job and the connection check script in place, your system will automatically monitor the Wi-Fi connection and restart the Network Manager if it detects that the connection is down. This ensures a more stable network connection and can be especially helpful in situations where you rely on a wireless network that occasionally drops out.

Remember to adjust the cron schedule according to your needs. For more frequent checks, you can decrease the time interval, and for less frequent checks, increase it.

0%