如何在脚本中使用ping

时间:2009-11-13 08:32:22

标签: bash ssh ping

我想要一个bash脚本:

for c in computers:
do
   ping $c
   if ping is sucessfull:
      ssh $c 'check something'
done

如果我只做ssh并且计算机没有响应,那么超时需要永远。所以我在考虑使用ping的输出来查看计算机是否存活。我怎么做?其他想法也会很棒

9 个答案:

答案 0 :(得分:16)

使用ping的返回值:

for C in computers; do
  ping -q -c 1 $C && ssh $C 'check something'
done
如果单个ping(ping)成功,

-c 1将以值0退出。在ping超时时,或者如果无法解析$C,它将以非零值退出。

答案 1 :(得分:8)

-w命令上使用-t开关(或FreeBSD和OS X上的ping),然后检查命令的返回值。

ping -w 1 $c
RETVAL=$?
if [ $RETVAL -eq 0 ]; then
    ssh $c 'check something'
fi

如果您要连接的主机距离较远且延迟较高,则可能需要调整您使用-w传递的参数。

来自man ping

   -w deadline
          Specify  a  timeout, in seconds, before ping exits regardless of
          how many packets have been sent or received. In this  case  ping
          does  not  stop after count packet are sent, it waits either for
          deadline expire or until count probes are answered or  for  some
          error notification from network.

答案 2 :(得分:4)

并非所有网络环境都允许ping通过(尽管有很多),并非所有主机都会回答ping请求。我建议不要使用ping,而是设置ssh的连接超时:

for c in compuers; do
  ssh -o ConnectTimeout=2 $c 'check something'
done

答案 3 :(得分:0)

我大约10年前写过这个剧本:

http://www.win.tue.nl/~rp/bin/rshall

您可能不需要确定每个可到达主机的部分,并迭代每个主机。

答案 4 :(得分:0)

使用64值作为测量工具是不合逻辑的。最好使用接收/丢失数据包的数量。

这个脚本可行:

RESULT="1"
PING=$(ping ADDRESS -c 1 | grep -E -o '[0-9]+ received' | cut -f1 -d' ')
if [ "$RESULT" != "$PING" ]
then
    DO SOMETHING
else
    DO SOMETHING
fi

答案 5 :(得分:0)

这是我的黑客:

#ipaddress shell variable can be provided as an argument to the script.
while true
do
   nmap_output=$(nmap -p22 ${ipaddress})
   $(echo ${nmap_output} | grep -q open)
   grep_output=$?
   if [ "$grep_output" == 0 ] ; then
       #Device is LIVE and has SSH port open for clients to connect
       break
   else
       #[01 : bold
       #31m : red color
       #0m : undo text formatting
       echo -en "Device is \e[01;31mdead\e[0m right now .... !\r"
   fi
done
#\033[K : clear the text for the new line
#32 : green color
echo -e "\033[KDevice is \e[01;32mlive\e[0m !"
ssh user@${ipaddress}

不仅仅依赖于ping。为什么? - 成功ping并不能保证您ssh访问成功。您仍然可以将ping测试添加到此脚本的开头,如果ping失败则退出,并且不执行上述操作。

以上bash脚本代码段,验证您正在尝试使用的设备    访问具有SSH端口,供客户端(您)连接。需要安装nmap个包。

我不明白你为什么要ssh进入该脚本中的多台计算机。但是,我的ssh工作在一个设备,可以修改,以满足您的需求。

答案 6 :(得分:0)

认识到原始问题引用了Bash,这是一个希望在Fish shell中实现此目标的人的示例:

ping -q -c 1 bogus.local; and echo "pinging the host worked"; or echo "pinging the host didn't work"

答案 7 :(得分:0)

 while true;
    do
        RESULT="1"
        PING=$(ping 8.8.8.8 -c 1 | grep -E -o '[0-9]+ received' | cut -f1 -d' ')
        if [ "$RESULT" != "$PING" ]
        then
            echo "FAIL"
            exit 0
        else
            echo "connection is okay.." 
        fi
    done

答案 8 :(得分:-1)

在你的bash循环中使用它:

RESULT="64"
PING=$(ping 127.0.0.1 -c 1 | grep 64 | awk '{print $1}')
if [ "$RESULT" != "$PING" ]
then
   #ping failed
else
   #ping successful, do ssh here
fi
相关问题