通过 python subprocess.Popen ssh:如果需要密码则终止 [英] ssh via python subprocess.Popen: terminate if password requested
问题描述
我正在使用 python 脚本来管理工作站重新映像后的 ssh 指纹问题.
I'm using a python script to manage ssh fingerprint problems after a workstation(s) is reimaged.
我尝试与 ssh 连接,如果收到任何警告,我会处理它们.
I attempt to connect with ssh, and if I get a any warnings I deal with them.
但是,如果没有错误,那么我会被要求输入密码以进行连接.此时我想终止该过程.但是,脚本挂在密码请求上.
However, if there are no errors, then I am asked for a password to connect. At this point I want to terminate the process. However, the script hangs on the password request.
方法如下:
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,按预期继续执行脚本.
If I run this from the terminal ./my_python_script.py
, I have the problems. Oddly, if I run in PyCharm, it doesn't hang on the password request and terminates shh, continuing with the script as expected.
推荐答案
简单的答案就是告诉 ssh
你根本不想支持密码认证;如果主机密钥发生更改,您仍然会收到所需的消息,但您永远不会等待输入密码的进程挂起.
The easy answer is simply to tell ssh
that you don't want to support password authentication at all; you'll still get the messages you want if the host key is changed, but you won't ever have the process hanging waiting for a password to be entered.
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 传递给进程.
If you did not want to process other prompts, I would suggest setting stdin=subprocess.DEVNULL
(in Python 3) or passing the -n
argument to ssh to prevent stdin from being passed to the process at all.
这篇关于通过 python subprocess.Popen ssh:如果需要密码则终止的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!