在机器上使用Fabric运行ssh-add

5 投票
1 回答
1591 浏览
提问于 2025-04-17 04:20

我正在用Fabric执行一些部署任务,这些任务需要把一个Mercurial代码库下载到机器上,然后进行相应的复制和配置。

每次我创建一台新机器(我们现在使用EC2作为基础设施)或者在机器上运行hg pull时,它都会让我输入我的ssh密钥密码,这在我们需要同时初始化十几台机器的时候就有点麻烦了。

我试着在Fabric中运行ssh-add,当新的EC2实例初始化时,但似乎那个shell没有运行ssh-agent,所以我在Fabric的输出中收到了一个Could not open a connection to your authentication agent.的错误信息。

我该如何让ssh-add在通过Fabric脚本连接到实例时正常工作呢?

1 个回答

3

在fabric的问答平台上,有个评论帮我解决了这个问题。这个解决方案是对lincolnloop方案的一个修改版。使用这个“run”命令,而不是fabric自带的,可以让你的命令通过本地的ssh来执行,这样你的本地ssh-agent就能提供密钥。

from fabric.api import env, roles, local, output
from fabric.operations import _shell_escape

def run(command, shell=True, pty=True):
    """
    Helper function.
    Runs a command with SSH agent forwarding enabled.

    Note:: Fabric (and paramiko) can't forward your SSH agent. 
    This helper uses your system's ssh to do so.
    """
    real_command = command
    if shell:
        cwd = env.get('cwd', '')
        if cwd:
            cwd = 'cd %s && ' % _shell_escape(cwd)
        real_command = '%s "%s"' % (env.shell,
            _shell_escape(cwd + real_command))
    if output.debug:
        print("[%s] run: %s" % (env.host_string, real_command))
    elif output.running:
        print("[%s] run: %s" % (env.host_string, command))
    local("ssh -A %s '%s'" % (env.host_string, real_command))

请注意,我使用的是Fabric 1.3.2,这个修复不久后就不需要了。

撰写回答