首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >通过python子进程的ssh :指纹缺失时如何保释(确定要继续连接吗?)

通过python子进程的ssh :指纹缺失时如何保释(确定要继续连接吗?)
EN

Stack Overflow用户
提问于 2018-01-27 03:53:46
回答 1查看 844关注 0票数 0

在重新镜像工作站之后,我使用python脚本来管理ssh指纹问题。

我尝试连接,如果收到“远程主机标识已更改!”错误,然后脚本删除旧指纹,扫描新指纹并添加它。

这一切都运行得很好,直到我收到这样的消息:

代码语言:javascript
运行
复制
 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“,以便脚本可以继续其指纹修复作业?

下面是相关的方法:

代码语言:javascript
运行
复制
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
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-01-27 04:06:28

run (或遗留call)不允许您以交互方式控制流程的输入/输出。当您获得输出时,该过程已经结束。所以你来不及参加派对了。

有些人会将您引导到pexpectparamiko (它不需要调用ssh命令)。

这是Popen的一个变通方法。我把你的return逻辑弄丢了。如果您想保留它,请记住,此时该进程仍在运行,因此您必须终止它(或等待它完成):

代码语言:javascript
运行
复制
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",并且给定次数,那么循环的另一种选择将是

代码语言:javascript
运行
复制
out,err = p.communicate(b"no\n"*10)  # send 10 times no+linefeed

在扫描字符串/写入数据时,请注意"b“前缀,因为标准输入/输出/错误是二进制的。在Python2中没有关系,但是在Python3中,省略b将字符串与字节进行比较,并且永远不会得到匹配。

另外,我在Windows的plink上也做到了这一点,但过了一段时间,我感到疲惫,重新构建了一个版本的plink,所有安全消息都被禁用/默认设置为“乐观”值。如果网络是位于防火墙后面的公司网络,并且您要回答任何问题以通过这些提示,最好从一开始就创建一个非交互式工具。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/48468610

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档