Search code examples
pythonlinuxsshparamiko

How to use Paramiko with host definition in ~/.ssh/config?


For my SSH connections, I use this ~/.ssh/config:

Host gwhost
Hostname gw.hostname.com
User user
IdentityFile /home/user/.ssh/priv_key
ControlMaster auto
ControlPath ~/.ssh/%h-%p-%r.sock
ControlPersist 120

Host *.my-example.com
User user
IdentityFile /home/user/.ssh/priv_key
StrictHostKeyChecking no
ProxyCommand ssh -q 'gwhost' -W %h:22

From the terminal I can connect to the host like this:

ssh one.my-example.com

I want to execute some commands on a remote host using Paramiko. I tried to do it like this:

host = 'one.my-example.com'
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
user_config_file = os.path.expanduser("~/.ssh/config")
config = SSHConfig.from_path(user_config_file)

ssh.connect(hostname=host)
stdin, stdout, stderr = ssh.exec_command('ls')
lines = stdout.readlines()
print(lines)

After starting I got this error

in <lambda>
    retry_on_signal(lambda: sock.connect(addr))
TimeoutError: [Errno 110] Connection timed out

So how can I use ~/.ssh/config or maybe I shouldn't ~/.ssh/config?


Solution

  • Paramiko has only very limited support for OpenSSH ssh_config configuration file.

    It definitely won't use ssh_config automatically, the way OpenSSH ssh does.

    You would have to instantiate SSHConfig class using SSHConfig.from_path. And then use SSHConfig.lookup to lookup configuration for your hostname. And then use the returned dictionary to feed the arguments of SSHClient.connect.


    Obligatory warning: Do not use AutoAddPolicy – You are losing a protection against MITM attacks by doing so. For a correct solution, see Paramiko "Unknown Server".