我在 AWS 上使用 Amazon Linux。尝试使用 ssh 执行远程命令,如下所示:
% ssh somehost echo Hello World
@@@@@@@@@@@@@@@@@@@@@@@@@@@
@ WARNING: REMOTE HOST IDENTIFICATION HAS CHANGED! @
@@@@@@@@@@@@@@@@@@@@@@@@@@@
<ECHO IS NOT EXECUTED HERE>
% echo $? # last exit code
0
这是我所期望的(不需要修复警告,失败是设计使然)。但是,我需要知道我的远程命令是否执行。问题是 ssh 退出代码为 0,并且我的远程命令是动态的,原则上可以输出相同的文本(如果它尝试自行执行另一个远程命令,或读取某些日志文件)。
那么在这种情况下如何判断 SSH 是否连接失败呢?
答案1
你使用的是什么 shell 我使用 zsh 进行了测试,但 bash 会执行相同的输出?
➜ ~ ssh localhost echo Hello world
Hello world
➜ ~ echo $?
0
➜ ~ ssh localhost error
bash: error: command not found
➜ ~ echo $?
127
➜ ~
➜ ~ ssh localhost fake
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@ WARNING: REMOTE HOST IDENTIFICATION HAS CHANGED! @
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
IT IS POSSIBLE THAT SOMEONE IS DOING SOMETHING NASTY!
Someone could be eavesdropping on you right now (man-in-the-middle attack)!
It is also possible that a host key has just been changed.
The fingerprint for the ECDSA key sent by the remote host is
SHA256:vYFp+5TGBtJd9XgvTJdKbK2pQSFwARcnOHtAYWyCfCE.
Please contact your system administrator.
Add correct host key in /home/user/.ssh/known_hosts to get rid of this message.
Offending ECDSA key in /home/user/.ssh/known_hosts:1
remove with:
ssh-keygen -f "/home/user/.ssh/known_hosts" -R localhost
Password authentication is disabled to avoid man-in-the-middle attacks.
Keyboard-interactive authentication is disabled to avoid man-in-the-middle attacks.
bash: fake: command not found
➜ ~ echo $?
127