我想要一个bash脚本,它会做:
for c in computers:
do
ping $c
if ping is sucessfull:
ssh $c 'check something'
done
Run Code Online (Sandbox Code Playgroud)
如果我只这样做ssh并且计算机是反应迟钝的,那么超时需要永远.所以我在考虑使用输出ping来查看计算机是否存活.我怎么做?其他想法也会很棒
Ste*_*202 16
使用ping的返回值:
for C in computers; do
ping -q -c 1 $C && ssh $C 'check something'
done
Run Code Online (Sandbox Code Playgroud)
ping如果单个ping(-c 1)成功,则将以值0退出.在ping超时时,或者如果$C无法解析,它将以非零值退出.
在命令中使用-w开关(或-t在FreeBSD和OS X上)ping,然后检查命令的返回值.
ping -w 1 $c
RETVAL=$?
if [ $RETVAL -eq 0 ]; then
ssh $c 'check something'
fi
Run Code Online (Sandbox Code Playgroud)
-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.
Run Code Online (Sandbox Code Playgroud)
小智 6
并非所有网络环境都允许 ping 通(尽管很多都允许)并且并非所有主机都会响应 ping 请求。我建议不要使用 ping,而是为 ssh 设置连接超时:
对于计算机中的 c;做 ssh -o ConnectTimeout=2 $c '检查一下' 完毕
| 归档时间: |
|
| 查看次数: |
51086 次 |
| 最近记录: |