python 预期登录:远程主机标识已更改

python pexpect login: remote host identification has changed

我已经用 pexpect 制作了一个脚本,我可以在其中使用 ssh 登录,但有时在某些服务器上我得到:

@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@    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 the RSA host key has just been changed.
The fingerprint for the RSA key sent by the remote host is
3d:1b:02:9e:b2:b8:f0:f7:c6:4f:94:96:f6:e3:c0:d1.
Please contact your system administrator.
Add correct host key in /root/.ssh/known_hosts to get rid of this message.
Offending key in /root/.ssh/known_hosts:8
RSA host key for 10.10.10.69 has changed and you have requested strict checking.Host key verification failed.

脚本停止。

我知道可以通过以下方式传递此警告:

os.system('ssh-keygen -f "/home/alex/.ssh/known_hosts" -R %s' % (ip))

这是我的代码:

from pexpect import pxssh

try:
    s = pxssh.pxssh()
    s.login(ip, user, password)

如何从登录中获取输出以检查输出是否包含 WARNING: REMOTE HOST IDENTIFICATION HAS CHANGED 以便我可以使用上述命令。

来自pexpect docs

The pattern given to expect() may be a regular expression or it may also be a list of regular expressions. This allows you to match multiple optional responses. The expect() method returns the index of the pattern that was matched.

因此,您可以执行以下操作:

pattern_index = server.expect(["WARNING:", "Normal response"])

if pattern_index == 0:
    #handle the warning message
else:
    server.sendline(....)
    server.expect(....)