4

My OS is Linux Centos 6. Restart Network Service after lost ping

Basically, I need a watcher or a script that will detect no ping to/from another ip address and run service network restart after every minute or so.

I need to restart the network for various reasons.

  • Your link is up and ping fails? – Nils Apr 3 '14 at 15:16
3

Save this script to file and make it executable. Then run it in a cronjob.

Open your favorite editor and copy this script :

#!/bin/bash

# cron script for checking lan connectivity

# Ping count is set aggressively to 1, increase depending what you want.
PING_COUNT=1
#I'm assuming ping is installed.
PING="/bin/ping"


#Find the gateway IP address
GATEWAY_IP=`ip route | grep default | cut -d " " -f 3`
# ping test
$PING -n -c "$PING_COUNT" "$GATEWAY_IP" &>/dev/null

if [ "$?" -ge 1 ]
then
    # This will log a message in system log (see manpage).
    logger "Network access DOWN"

    service network restart
else
    logger "Network access OK"
fi

Save the file and name it checklan for example. Make it executable by type in cmdline :

chmod +x checklan

As root or using sudo, move the file to /usr/local/bin :

mv checklan /usr/local/bin

Using sudo or root, open a new file in /etc/cron.d

vi /etc/cron.d/netcheck

Press i Copy the the following line :

*/10 * * * * root /usr/local/bin/checklan

Save the change by typing :x

Restart cron as root or using sudo :

service crond restart

Then the script should run every 10 mins. NOTE: Please read on the Internet about cron to understand syntax. You can increase rate up to every min.

Check /var/log/messages or /var/log/syslog to see if it is working:

tail -f /var/log/messages

If it works you will see something like this:

Apr  1 20:04:01 <hostname> logger: checklan OK
  • than kyou, how do I make it executable? – user3265051 Apr 1 '14 at 0:58
  • chmod +x <name of script>. – slm Apr 1 '14 at 1:14
  • I did read linfo.org/create_shell_1.html but still confused.. – user3265051 Apr 1 '14 at 1:18
  • This is a newbie user. Do you really want to gice him that trigger happy gun? – Nils Apr 3 '14 at 15:18
  • @Nils. If the script was deleting things i could understand your point but this is not the case here. Besides this should not be implemented in prod env without testing. It is provided fas a workaround or for learning purpose. – UnX Apr 3 '14 at 18:34

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.