在Python结构中将env.user和env.key_文件名设置为全局

在Python结构中将env.user和env.key_文件名设置为全局,python,fabric,Python,Fabric,我有几个Fabric任务,我想作为用户其他用户运行。比如说, install.py- def install_vim_on_host(): cmd = 'apt get install vim' result = sudo(cmd, user=env.user) install_vim_on_host从使用Fabric的execute()方法的函数调用- 我希望能够在其他python模块中使用env.user。在我的主目录中,我有一个其他用户的私钥,因此我将以下代码放在所有其他

我有几个Fabric任务,我想作为用户
其他用户运行。比如说,

install.py-

def install_vim_on_host():
    cmd = 'apt get install vim'
    result = sudo(cmd, user=env.user)
install_vim_on_host
从使用Fabric的execute()方法的函数调用-

我希望能够在其他python模块中使用
env.user
。在我的主目录中,我有一个
其他用户的私钥
,因此我将以下代码放在所有其他模块中加载的第一个模块的开头-

# setup some-other-user's identity
env.user = 'some-other-user'
cmd = 'echo $HOME'
with hide('running', 'stdout', 'stderr') :
    home_dir = local(cmd, capture=True)
env.key_filename = '%s/.ssh/some_other_user_rsa.pk' %(home_dir)
if not os.path.exists(env.key_filename):
    print 'private key of user some-other-user is not found'
    sys.exit()

这似乎工作得很好,但我想把上面的设置代码放在一个函数中,而不是像放在我的一个模块中那样。是否有任何方法可以实现这一点,使得env.user和env.key_文件名成为全局文件,并且可以从任何模块中的任何函数进行访问?

您可以在
$HOME/.ssh/config
中为该其他用户的特定主机设置所有这些内容,并告诉fabric使用全局
env.use_ssh_config=True

$HOME/.ssh/config

Host remote_host_type*
    User some-other-user
    IdentityFile ~/.ssh/some_other_user_rsa.pk
如果您不希望全局设置此值,则可以使用
--ssh config path=path

其他选项可能包括让函数全局运行和/或仅使用
\uuuu name\uuuuu
的知识来确定文件是否已运行或导入,以了解何时调用所要调用的函数

Host remote_host_type*
    User some-other-user
    IdentityFile ~/.ssh/some_other_user_rsa.pk