开发者

Making bash script to check connectivity and change connection if necessary. Help me improve it?

My connection is flaky, however I have a backup one. I made some bash script to check for connectivity and change co开发者_JAVA百科nnection if the present one is dead. Please help me improve them.

The scripts almost works, except for not waiting long enough to receive an IP (it cycles to next step in the until loop too quick). Here goes:

#!/bin/bash
# Invoke this script with paths to your connection specific scripts, for example
# ./gotnet.sh ./connection.sh ./connection2.sh

until [ -z "$1" ]  # Try different connections until we are online...
    do
    if eval "ping -c 1 google.com"
    then
        echo "we are online!" && break
    else
    $1     # Runs (next) connection-script.
    echo
    fi
     shift
   done

   echo               # Extra line feed.
exit 0

And here is an example of the slave scripts:

#!/bin/bash
ifconfig wlan0 down
ifconfig wlan0 up
iwconfig wlan0 key 1234567890
iwconfig wlan0 essid example
sleep 1
dhclient -1 -nw wlan0
sleep 3
exit 0


Here's one way to do it:

#!/bin/bash
while true; do
        if ! [ "`ping -c 1 google.com; echo $?`" ]; then #if ping exits nonzero...
                ./connection_script1.sh #run the first script
                sleep 10     #give it a few seconds to complete
        fi
        if ! [ "`ping -c 1 google.com; echo $?`" ]; then #if ping *still* exits nonzero...
                ./connection_script2.sh #run the second script
                sleep 10     #give it a few seconds to complete
        fi
        sleep 300 #check again in five minutes
done

Adjust the sleep times and ping count to your preference. This script never exits so you would most likely want to run it with the following command:

./connection_daemon.sh 2>&1 > /dev/null & disown


Have you tried omitting the -nw option from the dhclient command?

Also, remove the eval and quotes from your if they aren't necessary. Do it like this:

if ping -c 1 google.com > /dev/null 2>&1


Trying using ConnectTimeout ${timeout} somewhere.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜