First, why restart eth0 if the destination address is unreachable? This does not necessarily mean that eth0 is down. It could be that the host is unreachable for a number of different reasons.
That being asked, there a two ways of doing this. The first is the simplest and can be achieved by a script that runs the ping command every 3 seconds and logs the result. You can then set this script to automatically run when you log in. Here is a simple script (assuming you're using BASH):
Code:
#! /bin/bash
dest_IP='a.b.c.d'
success_file='/path/to/success/log/file'
fail_file='/path/to/fail/log/file'
while true
ping -q -c1 "$dest_IP" > /dev/null
if [ $? = 0 ]; then
echo "$dest_IP reached on $(date)" >> "$success_file"
else
echo "$dest_IP unreachable on $(date)" >> "$fail_file"
ifconfig eth0 down #Assumes you're using ifconfig and not NetworkManager
ifconfig eth0 up
fi
sleep 3s #Wait 3 seconds
loop
Because of the ifconfig, you may need to run this as root.
The second and what I believe is the better way, is to create cronjob. First create a script as above, but slightly modified:
Code:
#! /bin/bash
dest_IP='a.b.c.d'
success_file='/path/to/success/log/file'
fail_file='/path/to/fail/log/file'
ping -q -c1 "$dest_IP" > /dev/null
if [ $? = 0 ]; then
echo "$dest_IP reached on $(date)" >> "$success_file"
else
echo "$dest_IP unreachable on $(date)" >> "$fail_file"
ifconfig eth0 down #Assumes you're using ifconfig and not NetworkManager
ifconfig eth0 up
fi
Now create a crontab file with the
crontab -e command:
Code:
# This crontab file runs the script that pings a particular host every 3 seconds
#
*/3 * * * * /absolute/path/to/ping/script
The cronjob will run your script every 3 seconds.
I have not tested the script so they may need tweaking.
How it puts on the right track.