制作 bash 脚本以检查连接并在必要时更改连接。帮我改进一下?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2531583/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Making bash script to check connectivity and change connection if necessary. Help me improve it?
提问by cypherpunks
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.
我的连接不稳定,但我有一个备份。我制作了一些 bash 脚本来检查连接并在当前连接已死的情况下更改连接。请帮助我改进它们。
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:
脚本几乎可以工作,除了没有等待足够长的时间来接收 IP(它循环到直到循环中的下一步太快)。开始:
#!/bin/bash
# Invoke this script with paths to your connection specific scripts, for example
# ./gotnet.sh ./connection.sh ./connection2.sh
until [ -z "" ] # Try different connections until we are online...
do
if eval "ping -c 1 google.com"
then
echo "we are online!" && break
else
# 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
回答by musashiXXX
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:
根据您的喜好调整睡眠时间和 ping 计数。此脚本永远不会退出,因此您很可能希望使用以下命令运行它:
./connection_daemon.sh 2>&1 > /dev/null & disown
./connection_daemon.sh 2>&1 > /dev/null & disown
回答by Paused until further notice.
Have you tried omitting the -nwoption from the dhclientcommand?
您是否尝试-nw从dhclient命令中省略该选项?
Also, remove the evaland quotes from your ifthey aren't necessary. Do it like this:
此外,eval从您if不需要的和引号中删除它们。像这样做:
if ping -c 1 google.com > /dev/null 2>&1
回答by seasonedgeek
Trying using ConnectTimeout ${timeout} somewhere.
尝试在某处使用 ConnectTimeout ${timeout}。

