ssh通过python subprocess.Popen:如果请求密码则终止

时间:2018-01-26 21:37:34

标签: python ssh subprocess

我正在使用python脚本来管理工作站重新映像后的ssh指纹问题。

我尝试连接ssh,如果我收到任何警告,我会处理它们。

但是,如果没有错误,则会要求我输入密码进行连接。此时我想终止该过程。但是,该脚本会挂起密码请求。

以下是方法:

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.
    """
    changed = False
    cmd = ["ssh", "-q", ADMIN_USER + "@" + node, "exit"]
    proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stdin=subprocess.PIPE, universal_newlines=True)
    print("Checking for fingerprint changes")

    for line in proc.stdout:  # loop on lines
        print("in for loop") # NEVER REACHES HERE IF NO ERRORS, WAITING FOR PASSWORD
        if b"Offending key" in line:
            print("Offending key found.")
            proc.stdin.write(b"no\n")   # don't connect
            changed = True
        elif b"REMOTE HOST IDENTIFICATION HAS CHANGED!" in line:
            print("REMOTE HOST IDENTIFICATION HAS CHANGED!")
            changed = True

    print(changed) # NEVER REACHES HERE IF NO ERRORS, WAITING FOR PASSWORD
    if not changed:  # then everything's good, but it will be waiting for a password to connect
        print("Good to go, terminating ssh test.")
        rc = proc.terminate()
    else:
        rc = proc.wait()

    return changed

如果我从终端./my_python_script.py运行这个,我有问题。奇怪的是,如果我在PyCharm中运行,它不会挂起密码请求并终止shh,继续按预期运行脚本。

1 个答案:

答案 0 :(得分:0)

简单的答案就是告诉ssh您根本不想支持密码验证;如果主机密钥被更改,您仍然会收到所需的邮件,但您不会让进程等待输入密码。

cmd = ['ssh',
       '-o', 'PasswordAuthentication no',  ### <-- THIS LINE HERE
       '-o', 'StrictHostKeyChecking yes',  ### also, never modify known_hosts
       '-q',
       '%s@%s' % (ADMIN_USER, + node),
       'exit']

如果你不想处理其他提示,我建议设置stdin=subprocess.DEVNULL(在Python 3中)或将-n参数传递给ssh以防止stdin被传递给进程。

相关问题