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

这一生的挚爱 提交于 2019-12-24 04:51:49

问题


My connection is flaky, however I have a backup one. I made some bash script to check for connectivity and change connection 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

回答1:


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




回答2:


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



回答3:


Trying using ConnectTimeout ${timeout} somewhere.



来源:https://stackoverflow.com/questions/2531583/making-bash-script-to-check-connectivity-and-change-connection-if-necessary-hel

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!