我有一个脚本,可以创建虚拟机并返回 IP 地址。然后我想做这样的事情:
waitforssh 192.168.2.38 && ssh 192.168.2.38
它将等待机器启动并且 ssh 响应,然后 ssh 进入。
等待forssh是我需要找到的命令。
nmap、netcat、fping 或 ping 能完成这项工作吗?我尝试了 netcat,但如果主机无法访问,它只会在几秒钟内放弃。
它需要处理机器本身正在启动并且可能需要一些时间来响应网络数据包的事实。
答案1
我没有可以通过 ssh 连接并控制其是否启动的主机,但是这应该可行:
while ! ssh <ip>
do
echo "Trying again..."
done
或者更明确的 shell 脚本:
#!/bin/sh
ssh $1
while test $? -gt 0
do
sleep 5 # highly recommended - if it's in your local network, it can try an awful lot pretty quick...
echo "Trying again..."
ssh $1
done
将其另存为(例如)waitforssh.sh
,然后调用它sh waitforssh.sh 192.168.2.38
答案2
这是我正在使用的“ping_ssh”脚本。它可以处理超时情况,快速成功,并且不会像基于“nc”的解决方案那样提示输入密码或被端口打开但没有响应所欺骗。这结合了在各种 stackoverflow 相关网站上找到的几个答案。
#!/usr/bin/bash
HOST=$1
PORT=$2
#HOST="localhost"
#PORT=8022
if [ -z "$1" ]
then
echo "Missing argument for host."
exit 1
fi
if [ -z "$2" ]
then
echo "Missing argument for port."
exit 1
fi
echo "polling to see that host is up and ready"
RESULT=1 # 0 upon success
TIMEOUT=30 # number of iterations (5 minutes?)
while :; do
echo "waiting for server ping ..."
# https://serverfault.com/questions/152795/linux-command-to-wait-for-a-ssh-server-to-be-up
# https://unix.stackexchange.com/questions/6809/how-can-i-check-that-a-remote-computer-is-online-for-ssh-script-access
# https://stackoverflow.com/questions/1405324/how-to-create-a-bash-script-to-check-the-ssh-connection
status=$(ssh -o BatchMode=yes -o ConnectTimeout=5 ${HOST} -p ${PORT} echo ok 2>&1)
RESULT=$?
if [ $RESULT -eq 0 ]; then
# this is not really expected unless a key lets you log in
echo "connected ok"
break
fi
if [ $RESULT -eq 255 ]; then
# connection refused also gets you here
if [[ $status == *"Permission denied"* ]] ; then
# permission denied indicates the ssh link is okay
echo "server response found"
break
fi
fi
TIMEOUT=$((TIMEOUT-1))
if [ $TIMEOUT -eq 0 ]; then
echo "timed out"
# error for jenkins to see
exit 1
fi
sleep 10
done
答案3
像这样简单的事情就可以完成工作,在尝试之间等待 5 秒钟并丢弃 STDERR
until ssh <host> 2> /dev/null
do
sleep 5
done
答案4
嗯,我不太明白你的意思起来, 但是关于:
$ ping host.com | grep --line-buffered "bytes from" | head -1 && ssh host.com
第一个命令ping | ... | head -1
等待服务器发送单个 ping 回复并退出。然后 ssh 开始起作用。请注意,grep
可以缓冲输出,所以这就是它--line-buffered
的用途。
您可以用 bash 函数包装此命令,以便按照您描述的方式使用它。
$ waitfor() { ping $1 | grep --line-buffered "bytes from" | head -1 }
$ waitfor server.com && ssh server.com