我使用的是 Python 3.6 和 Fabric 2.4。我正在使用 Fabric 通过 SSH 连接到服务器并运行一些命令。我需要为远程服务器上运行的命令设置一个环境变量。文档表明这样的事情应该有效:
from fabric import task
@task(hosts=["servername"])
def do_things(c):
c.run("command_to_execute", env={"KEY": "VALUE"})
但这不起作用。像这样的事情也应该是可能的:
from fabric import task
@task(hosts=["servername"])
def do_things(c):
c.config.run.env = {"KEY": "VALUE"}
c.run("command_to_execute")
但这也行不通。我觉得我错过了什么。任何人都可以帮忙吗?
最佳答案
正如 Fabric 网站上所述:
The root cause of this is typically because the SSH server runs non-interactive commands via a very limited shell call: /path/to/shell -c "command" (for example, OpenSSH). Most shells, when run this way, are not considered to be either interactive or login shells; and this then impacts which startup files get loaded.
您在本页阅读更多 link
因此,您尝试执行的操作不起作用,解决方案是传递要显式设置的环境变量:
from fabric import task
@task(hosts=["servername"])
def do_things(c):
c.config.run.env = {"KEY": "VALUE"}
c.run('echo export %s >> ~/.bashrc ' % 'ENV_VAR=VALUE' )
c.run('source ~/.bashrc' )
c.run('echo $ENV_VAR') # to verify if it's set or not!
c.run("command_to_execute")
关于python - Fabric2 中的环境变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52670011/