Fabric无法正确处理env.key_filename

时间:2013-05-22 15:11:39

标签: python fabric

我正在运行Fabric 1.6.0(paramiko 1.10.1)。我有以下脚本:

from fabric.api import env, output, run, sudo

user='your-user'
host='your-server'
port='your-port'
command = 'ps -ef'

output['running']  = False     # Avoid fabric to output what it is doing behind the scenes
output['stdout']   = False     # Do not show stdout
output['stderr']   = False     # Do not show stderr
output['status']   = False     # Prevent fabric from using print in some situations (at least in disconnect_all)
output['warnings'] = False     # Avoid fabric from showing messages about failed commands

def run_it(command, user, host, port, keyfile):
    env.host_string = "%s@%s:%s" % (user, host, port)
    env.key_filename = keyfile
    try:
        res = run(command, pty=False, shell=True)
        print "SUCCESS: return_code=%s" % (return_code)
    except Exception, e:
        print "ERROR  : %s" % (e)
        stdout, return_code =  None, None
    return stdout, return_code

run_it(command, user, host, port, '/bad/keyfile')
run_it(command, user, host, port, '/home/gonvaled/.ssh/id_rsa')
run_it(command, user, host, port, '/bad/keyfile')

输出:

ERROR  : [Errno 2] No such file or directory: '/bad/keyfile'
SUCCESS: return_code=0
SUCCESS: return_code=0

但我期待:

ERROR  : [Errno 2] No such file or directory: '/bad/keyfile'
SUCCESS: return_code=0
ERROR  : [Errno 2] No such file or directory: '/bad/keyfile'

为什么会这样?看起来好的密钥文件是记住?为什么?这很烦人,因为它表明我无法动态设置密钥文件,所以我不确定使用哪一个:我设置的第一个,我设置的第二个?选择它的标准是什么?有多少人被记住? ...

我使用fabric作为ssh库(不在fabfiles中),所以我用不同的参数调用它。我依靠env将这些参数传递给fabric。这大部分工作正常,但key_filename似乎是一个例外。

2 个答案:

答案 0 :(得分:1)

查看代码,我想这是因为连接成功后会缓存。这意味着第一次成功的尝试将被记住,并且不会尝试新的密钥文件。

答案 1 :(得分:0)

我认为这是一个ssh问题,而不是结构问题。在第二次尝试成功连接后,密钥将存储在~/.ssh/known_hosts中,第三次尝试时,它会再次使用存储的密钥进行连接。我会尝试设置这两个选项之一,看看它是否再次发生:

env.no_keys = True
env.use_ssh_config = False