在重新镜像工作站之后,我使用python脚本来管理ssh指纹问题。
我尝试连接,如果收到“远程主机标识已更改!”错误,然后脚本删除旧指纹,扫描新指纹并添加它。
这一切都运行得很好,直到我收到这样的消息:
Warning: the ECDSA host key for 'workstation-1-s' differs from the key for the IP address '192.168.1.132'
Offending key for IP in /home/me/.ssh/known_hosts:16
Matching host key in /home/me/.ssh/known_hosts:60
Are you sure you want to continue connecting (yes/no)?脚本等待用户输入,然后继续并删除有问题的键。
如何让脚本推送通过,或输入"no“,以便脚本可以继续其指纹修复作业?
下面是相关的方法:
def ssh_fingerprint_changed(node):
"""
Checks if a node's ssh fingerprint has changed or an old key is found, which can occur when a node is reimaged.
It does this by attempting to connect via ssh and inspecting stdout for an error message.
:param node: the ip or hostname of the node
:return: True if the node's fingerprint doesn't match the client's records. Else False.
"""
cmd = ["ssh", "-q", ADMIN_USER + "@" + node, "exit"]
completed = subprocess.run(cmd, stdout=subprocess.PIPE, universal_newlines=True)
if completed.stdout.find("REMOTE HOST IDENTIFICATION HAS CHANGED!") == -1:
print("REMOTE HOST IDENTIFICATION HAS CHANGED!")
return True
elif completed.stdout.find("Offending key") == -1:
print("Offending key found.") # need to type "no" before this prints
return True
return False发布于 2018-01-27 04:06:28
run (或遗留call)不允许您以交互方式控制流程的输入/输出。当您获得输出时,该过程已经结束。所以你来不及参加派对了。
有些人会将您引导到pexpect或paramiko (它不需要调用ssh命令)。
这是Popen的一个变通方法。我把你的return逻辑弄丢了。如果您想保留它,请记住,此时该进程仍在运行,因此您必须终止它(或等待它完成):
cmd = ["ssh", "-q", ADMIN_USER + "@" + node, "exit"]
p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stdin=subprocess.PIPE, universal_newlines=True)
# loop on lines
for l in p.stdout:
if b"Offending key" in l:
print("Offending key found.")
p.stdin.write(b"no\n") # provide no + newline as the answer
rc = p.wait() # wait for process to end, get return code如果您确定唯一的答案将是"no",并且给定次数,那么循环的另一种选择将是
out,err = p.communicate(b"no\n"*10) # send 10 times no+linefeed在扫描字符串/写入数据时,请注意"b“前缀,因为标准输入/输出/错误是二进制的。在Python2中没有关系,但是在Python3中,省略b将字符串与字节进行比较,并且永远不会得到匹配。
另外,我在Windows的plink上也做到了这一点,但过了一段时间,我感到疲惫,重新构建了一个版本的plink,所有安全消息都被禁用/默认设置为“乐观”值。如果网络是位于防火墙后面的公司网络,并且您要回答任何问题以通过这些提示,最好从一开始就创建一个非交互式工具。
https://stackoverflow.com/questions/48468610
复制相似问题