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


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

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

Host *
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:


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

host = ''
ssh = paramiko.SSHClient()
user_config_file = os.path.expanduser("~/.ssh/config")
config = SSHConfig.from_path(user_config_file)

stdin, stdout, stderr = ssh.exec_command('ls')
lines = stdout.readlines()

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?


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