Monitor and Automatically Restart a Network Interface on Ubuntu
When a web server goes down, a failed network card is often the culprit. If you can’t access your website or connect via SSH, that’s usually the problem. You can set up a scheduled script to monitor the network and automatically restart the networking service. Related article:How to Monitor and Automatically Restart Apache on Linux
1 Create the auto_restart_network.sh Script
The script contents are as follows:
#!/bin/bash ping www.baidu.com -c 1 >/dev/null if [ $? -ne 0 ];then # systemctl restart network sudo /etc/init.d/networking restart echo `date` network restart >> /alidata/tools/network_restart_logs.txt else echo `date` network works fine fi
Upload this file to the server.
Notes:
1) The script pings www.baidu.com. You can change it to another site, such as your own.
2) If the ping fails, the script runs a command to restart the networking service.
2 Create a Scheduled Job
There are two ways to create a scheduled job. The first is to edit /etc/crontab directly. Run:
sudo vim /etc/crontab
Add the following at the end:
*/30 * * * * root /alidata/tools/auto_restart_network.sh >> /alidata/tools/logs.txt 2>&1
Here, */30 means the script runs every 30 minutes.
The crontab time fields are explained below:
# .---------------- minute (0 - 59) # | .------------- hour (0 - 23) # | | .---------- day of month (1 - 31) # | | | .------- month (1 - 12) OR jan,feb,mar,apr ... # | | | | .---- day of week (0 - 6) (Sunday=0 or 7) OR #sun,mon,tue,wed,thu,fri,sat # | | | | | # * * * * * command to be executed
The other way is to run this command:
crontab -e
Add the following at the end:
*/30 * * * * /alidata/tools/auto_restart_network.sh >> /alidata/tools/logs.txt 2>&1
As I understand it, the first method adds a system-wide scheduled job, so you need to specify root as the user after the time fields. The second method adds a job for the current user. Either method works.
Restart the scheduling service:
sudo service crond restart
If all goes well, the script will run every 30 minutes. You can find the script’s execution log in /alidata/tools/network_restart_logs.txt and the output from each run in /alidata/tools/logs.txt. Since the script runs infrequently and outputs only a few characters, these two log files generally won’t grow much, but you should still clear them out periodically.
Appendix: Networking Service Commands
The commands for managing the networking service on Ubuntu are as follows:
Start the networking service
sudo /etc/init.d/networking start
Stop the networking service
sudo /etc/init.d/networking stop
Restart the networking service
sudo /etc/init.d/networking restart
References
https://www.cyberciti.biz/faq/linux-restart-network-interface/