python ssh密码提示 [英] python ssh password prompt

查看:26
本文介绍了python ssh密码提示的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在使用 ssh 时根据提示自动传递密码.通常,rsa 密钥用于防止密码提示,但我不能保证每个用户都设置正确,所以我希望脚本在用户提供时自动设置密码

I am trying to get automatic password passing upon prompt while using ssh. normally, rsa keys are used to prevent password prompt but I can't guarantee every user is set up properly so i want the script to automatically set the password if given by the user

这里是

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 将始终自动返回所需的密码,而无需用户自己输入密码.

This is not working as requesting password is still prompted. The idea is that GetPass replacing sys.stdin will always return the desired password automatically without the user typing it himself.

任何想法或解决方案?

推荐答案

SSH 从终端读取密码,而不是从 stdin,因此您无法使用 subprocess.Popen 提供合成(未提示)密码.

SSH reads the password from the terminal, not from stdin, so there's no way you can provide a synthetic (not prompted) password using subprocess.Popen.

我知道不想为您的应用程序加载依赖项,但我也为此推荐 paramiko.如果没有它,您正在考虑使用像 pyexpect 这样的工作流管理器来处理 fabric,除非您自己使用伪终端来实现整个工作流.你可以在不引入依赖的情况下做到这一点,但坦率地说,不值得为错误或行为分歧增加额外的表面积.

I understand not wanting to lade your application with dependencies, but I also would recommend paramiko for this. Without that, you're looking at using a workflow manager like pyexpect for fabric anyway, unless you implement the whole workflow yourself using a pseudoterminal. You can do that without introducing dependencies, but frankly it's not worth the extra surface area for bugs or behavior divergence.

不过,如果您想尝试一下,这里是概述方法的要点.您可以将其简化很多,但它可以理解基本要素.

Still, if you want to try it, here's a gist that outlines an approach. You could simplify this quite a lot but it gets the essentials across.

这篇关于python ssh密码提示的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆