我试图在使用 ssh 时根据提示自动传递密码。 通常,rsa key 用于防止密码提示,但我不能保证每个用户都正确设置,因此我希望脚本在用户给出密码时自动设置密码
这是
ssh = subprocess.Popen(["ssh", "localhost", "python -c 'print \"I am running\"' "], shell=False,stdout=subprocess.PIPE,stderr=subprocess.PIPE)
>>> Password:
我尝试过的解决方案是
import sys, subprocess
class GetPass():
def __init__(self, password):
self.password=str(password)
def readline(self):
return self.password
sys.stdin = GetPass('mypassword')
# test raw_input 3 time to verify
raw_input()
>> 'mypassword'
raw_input()
>> 'mypassword'
raw_input()
>> 'mypassword'
# Now try sshing again
ssh = subprocess.Popen(["ssh", "localhost", "python -c 'print \"I am running\"' "], shell=False,stdout=subprocess.PIPE,stderr=subprocess.PIPE)
>>> Password:
这不起作用,因为仍然提示请求密码。 这个想法是 GetPass 替换 sys.stdin 将始终自动返回所需的密码,而无需用户自己输入。
有什么想法或解决方案吗?
最佳答案
SSH 从终端读取密码,而不是从标准输入读取密码,因此您无法使用 subprocess.Popen
提供合成(不提示)密码。
我知道不想让您的应用程序充满依赖项,但我也建议使用paramiko
。如果没有它,您无论如何都会考虑使用像 pyexpect
这样的工作流程管理器来处理 fabric
,除非您自己使用伪终端实现整个工作流程。您可以在不引入依赖项的情况下做到这一点,但坦率地说,不值得为错误或行为分歧而花费额外的表面积。
不过,如果你想尝试一下,这里是 a gist that outlines an approach 。您可以将其简化很多,但它涵盖了要点。
关于python ssh 密码提示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46004848/