python - Fabric2 中的环境变量

标签 python fabric

我使用的是 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/

相关文章:

python - 如何使用 python 结构对远程服务器上存在的文件进行更改/编辑?

python - 在使用从列表中计算出最接近数字的代码时遇到问题

python - 使用循环将大数据写入 Excel 列单元格

python - 将 matplotlib quiver 和 elipses 结合起来不起作用

python - 在没有命令行工具 (fab) 的情况下使用 Python Fabric

python - 如何使用 Fabric 将目录复制到远程计算机?

python - 在 Windows 上的 fabfile 中使用 activate_this.py 激活 python 虚拟环境

python - 如何将Python变量组合成单行数据框?

python - 如何在大量文件中将一个类替换为另一个模块中的另一个类,而无需进行大量手动编辑?

python - 为什么我的 Python 脚本编写的是 Windows 风格的回车符?