Python结构和密码提示

2024-05-13 09:20:52 发布

您现在位置:Python中文网/ 问答频道 /正文

我看到有一些关于结构和密码的问题。我知道,如果将-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连接,而fabric对此无能为力。

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

获取过程信息:

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'

Tags: runtest命令服务器脚本密码远程环境变量
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(...)输入东西,就好像您在另一台机器上一样,所以是的,应该可以工作吗?

调试(只需启动一个命令提示符,导航到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'
>>>

我就是这样做的。简而言之:如果设置了^{},fabric将使用它连接到^{}中列出的服务器:

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...

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

相关问题 更多 >