Search code examples
pythonparamikossh-tunnelssh-agent

Paramiko or sshtunnel and ssh-agent without entering passphrase


I am trying to create a tunnel to a server with sshtunnel. I am using an ssh-key and ssh-agent:

from sshtunnel import SSHTunnelForwarder

with SSHTunnelForwarder(
    (proxyhost, 22),
    ssh_username=ssh_username,
    #ssh_private_key_password=PASSPHRASE, # with this line it works
    remote_bind_address=('127.0.0.1', 3306),
) as tunnel:
    pass

The correct private key is found, and when I give the passphrase as argument, the tunnel is established (see commented line above).

But I have already unlocked my ssh private key with ssh-agent (I am only asked for my ssh passphrase the very first time I use ssh after a reboot). Is it possible to have paramiko/sshtunnel get the unlocked private key without prompting for the passphrase? I'd like to avoid storing my passphrase anywhere on disk.


Solution

  • I was having trouble with this issue and finally came up with a solution. I was trying to use alembic to run migrations and needed to go through an ssh tunnel. SSHTunnel should access your agent if it's running, but it will also produce errors like this:

        ERROR [sshtunnel.SSHTunnelForwarder:1233][MainThread] Password is required for key  
    

    I was able to access the encrypted keys that are stored in the Keychain on macOS by importing paramiko and then using paramiko.agent.Agent().get_keys().

    Here is your updated code:

    from sshtunnel import SSHTunnelForwarder
    import paramiko
    
    with SSHTunnelForwarder(
        (proxyhost, 22),
        ssh_username=ssh_username,
        ssh_pkey=paramiko.agent.Agent().get_keys(),
        remote_bind_address=('127.0.0.1', 3306),
    ) as tunnel:
        pass