Skip to content

Instantly share code, notes, and snippets.

@khanhicetea
Last active August 29, 2015 14:05
Show Gist options
  • Save khanhicetea/4fe41fe3cf8075977685 to your computer and use it in GitHub Desktop.
Save khanhicetea/4fe41fe3cf8075977685 to your computer and use it in GitHub Desktop.
Auto recovery network settings CentOS if it fails.

Step 1 : Backup working settings folder

cp -R /etc/sysconfig/network-scripts /etc/sysconfig/network-scripts_bak

Step 2 : Create bash file at /root/network.sh with below content

#!/usr/bin/env bash

maxPloss=10

restart_networking() {
        mv /etc/sysconfig/network-scripts /etc/sysconfig/network-scripts_$(date +%F-%T)
        cp -R /etc/sysconfig/network-scripts_bak /etc/sysconfig/network-scripts
        /etc/init.d/network restart
}

if ! $(ping -w5 www.google.com > /dev/null 2>&1); then
        echo "Network connection is down, restarting network ..."
        restart_networking
        exit
fi

ploss=101
ploss=$(ping -q -w10 www.google.com | grep -o "[0-9]*%" | tr -d %) > /dev/null 2>&1

if [ "$ploss" -gt "$maxPloss" ]; then
        echo "Packet loss ($ploss%) exceeded $maxPloss, restarting network ..."
        restart_networking
        exit
fi


echo "Network is working fine :D ..."

And set it permission to run with this command

chmod +x /root/network.sh

Step 3: Create a cron job with root permission

crontab -e

And add auto checking job to it

*/5 * * * * /root/network.sh > /tmp/auto_recovery_network.log

Step 4: Enjoy it and not afraid to lose connection to server in DataCenter !!!

I used the idea of abibibo in this article.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment