在自动化期间无法在 Expect Shell 脚本中确定主机的真实性时如何忽略或传递 'Yes'

How to ignore or Pass 'Yes' when The authenticity of host can't be established in Expect Shell script during Automation

我想自动提供 'Yes' 或忽略它并以安全的方式继续,当在我的 Expect Shell 脚本执行期间出现以下语句时?

#!/usr/bin/expect
spawn ssh $user@$host

The authenticity of host 'abcdef (10.566.1.98)' can't be established. RSA key fingerprint is jk:94:ba:93:0b:eb:ff:df:ea:gh:hj:23:3c:hj:9c:be. Are you sure you want to continue connecting (yes/no)?

在这种情况下使用 exp_continue

#!/usr/bin/expect 
set prompt "#|>|\$"
spawn ssh dinesh@myhost
expect {
        #If 'expect' sees '(yes/no )', then it will send 'yes'
        #and continue the 'expect' loop
        "(yes/no)" { send "yes\r";exp_continue}
        #If 'password' seen first, then proceed as such.
        "password"
}
send "root\r"
expect -re $prompt

参考:Expect

可以通过将 ssh 客户端选项 StrictHostKeyChecking 设置为 no(默认设置为 ask,从而导致该问题)来避免此问题并自动接受所有传入的密钥:

ssh -o StrictHostKeyChecking=no "$user@$host"

但是请注意,这几乎没有任何安全性,因为您基本上接受与可能充当给定主机的每个人的连接。避免问题的唯一安全方法是将主机 public 密钥预先分发给客户端,即以预先生成的已知主机文件的形式,可以以某种方式使用:

ssh \
    -o UserKnownHostsFile=PATH_TO_YOUR_KNOWN_HOSTS_FILE \
    -o StrictHostKeyChecking=yes "$user@$host"

这样你就可以避免检查失败的问题,并且 ssh 将导致非零退出状态。

这行得通,对于 docker 构建特别方便

ssh-keyscan hostname.example.com >> $HOME/.ssh/known_hosts