Search code examples
pythonsshfabric

How to initiate SSH connection from within a Fabric run command


I have a remote server, say 1.2.3.4which is running a docker container that is serving SSHD mapped to port 49222 on the docker host, so to connect to it manually I would do:

workstation$ ssh 1.2.3.4 -t "ssh root@localhost -p 49222" and arrive at the docker container SSH command prompt root@f383b4f71eeb:~#

If I run a fabric command which triggers run('ssh root@localhost -p 49222') then I instead am asked for the root password. However it does not accept the root password which I know to be correct, so I suspect the password prompt is originating from the host and not the docker container.


Solution

  • I defined the following task in my fabfile.py:

    @task
    def ssh():
        env.forward_agent = True
        run('ssh root@localhost -p 49222')
        with settings(output_prefix=False, forward_agent=True):
            run('ssh root@localhost -p 49222')
    

    And in the remote servers sshd_config I needed to set:

    AllowAgentForwarding yes
    

    In addition, the output_prefix=False is useful to remove the [hostname] run: prefix that fabric adds to the start of every line, which is fairly annoying for every line of a remote shell.