【问题标题】:Making bash script to check connectivity and change connection if necessary. Help me improve it?制作 bash 脚本来检查连接并在必要时更改连接。帮我改进一下?
【发布时间】:2010-03-28 01:25:47
【问题描述】:

我的连接不稳定,但我有一个备用的。我制作了一些 bash 脚本来检查连接并在当前连接已死时更改连接。请帮助我改进它们。

脚本几乎可以工作,除了没有等待足够长的时间来接收 IP(它循环到直到循环中的下一步太快)。如下:

#!/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

下面是从属脚本的示例:

#!/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

【问题讨论】:

    标签: bash connectivity


    【解决方案1】:

    这是一种方法:

    #!/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
    

    根据您的喜好调整睡眠时间和 ping 计数。此脚本永远不会退出,因此您很可能希望使用以下命令运行它:

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

    【讨论】:

      【解决方案2】:

      您是否尝试过在dhclient 命令中省略-nw 选项?

      另外,删除 eval 和 if 中的引号,它们不是必需的。这样做:

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

      【讨论】:

        【解决方案3】:

        尝试在某处使用 ConnectTimeout ${timeout}。

        【讨论】:

          猜你喜欢
          • 2010-11-27
          • 1970-01-01
          • 2021-09-02
          • 1970-01-01
          • 2015-10-12
          • 2017-08-08
          • 1970-01-01
          • 1970-01-01
          • 2011-05-26
          相关资源
          最近更新 更多