Python Fabric和密码提示

时间:2013-05-13 18:49:04

标签: python ssh fabric

我看到有关于结构和密码的一些问题。我知道如果我将-I传递给fabric,那么我输入的密码将被传递给环境变量“password”。问题是我在远程服务器上运行ssh命令到另一台远程服务器时提示输入密码。

但是,我不希望系统提示输入密码。无论我尝试做什么,我都会被提示。所以这里有一小段代码:

elif "test" in run('hostname -d'):
                print(blue("Gathering Knife info"))
                run("ssh mychefserver knife node show `hostname`.test.dmz")

输入密码时效果很好。问题是,我不想输入我的密码。也许这是因为在远程主机上启动了另一个ssh连接,并且结构无法对此做任何事情。

我可以让脚本与远程主机断开连接,在本地运行ssh命令,然后重新连接到远程主机以完成脚本......但这看起来很愚蠢。建议?

Getpass信息:

Python 2.6.6 (r266:84292, Sep 11 2012, 08:34:23) 
[GCC 4.4.6 20120305 (Red Hat 4.4.6-4)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> from getpass import getpass
>>> getpass('test: ')
test: 
'This is a test'

3 个答案:

答案 0 :(得分:3)

from subprocess import Popen, PIPE
from getpass import getpass

x = Popen('ssh root@host', stdin=PIPE, stdout=PIPE, stderr=PIPE, shell=True)

print x.stdout.readline()
_pass = getpass('Enter your superduper password:')
x.stdin.write(_pass)
print x.stdout.readline()

连接后,您仍然可以通过x.stdin.write(...)输入内容,就像您在另一台机器上一样,那么,这应该有用吗?

DEBUG(只需启动一个cmd promt,导航到你的python目录并编写Python):

C:\Users>python
Python 2.7.3 (default, Apr 10 2012, 23:31:26) [MSC v.1500 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.

>>> from getpass import getpass
>>> getpass('test: ')
test:
'This is a test'
>>>

答案 1 :(得分:0)

我是这样做的。简而言之:如果您设置fabric.api.env.password,则Fabric会使用它连接到env.hosts中列出的服务器:

from getpass import getpass
from fabric.api import env

# Setting env.hosts
env.hosts = ['someuser@someserver.com']

def deploy():
    """A deployment script"""
    # Setting env.password with `getpass`
    # See here for more: http://fabric.readthedocs.org/en/1.8/usage/env.html#password
    env.password = getpass('Enter the password for %s: ' % env.hosts[0])
    # The rest of the script follows...

答案 2 :(得分:-1)

如果您不想输入密码,可以设置密钥对进行身份验证。您使用ssh-keygen生成公钥和私钥,将公钥放入远程计算机并使用私钥作为身份验证机制(https://en.wikipedia.org/wiki/Ssh-keygen)。