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

Issue

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.

If definitely won’t use ssh_config automatically, as 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".

Answered By – Martin Prikryl

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published