Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Connecting with paramiko using the user's OpenSSH config
client = paramiko.SSHClient()
client._policy = paramiko.WarningPolicy()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh_config = paramiko.SSHConfig()
user_config_file = os.path.expanduser("~/.ssh/config")
if os.path.exists(user_config_file):
with open(user_config_file) as f:
ssh_config.parse(f)
cfg = {'hostname': options['hostname'], 'username': options["username"]}
user_config = ssh_config.lookup(cfg['hostname'])
for k in ('hostname', 'username', 'port'):
if k in user_config:
cfg[k] = user_config[k]
if 'proxycommand' in user_config:
cfg['sock'] = paramiko.ProxyCommand(user_config['proxycommand'])
client.connect(**cfg)
@guettli

This comment has been minimized.

Copy link

guettli commented Dec 5, 2014

Why is this not in paramiko?

@kphretiq

This comment has been minimized.

Copy link

kphretiq commented Mar 23, 2016

Also, I have found that in some situations, one will need to explicitly supply the private key. Paramiko is always a first date for me. :-D

explicitly supply private key

user_config = ssh_config.lookup(persona)
with open(user_config["identityfile"][0], "rb") as keyobj:
    pkey = paramiko.RSAKey.from_private_key(keyobj)

    cfg = { 
            "hostname": user_config["hostname"],
            "username": user_config["user"],
            "port": int(user_config["port"]),
            "pkey": pkey,
            }
@koadjunky

This comment has been minimized.

Copy link

koadjunky commented May 17, 2016

For supplying private key the key_filename parameter can also be used:

if 'identityfile' in user_config:
    cfg['key_filename'] = user_config['identityfile']
@djhume

This comment has been minimized.

Copy link

djhume commented Jun 14, 2016

Thanks, this is great!

@Arun-Baskaran

This comment has been minimized.

Copy link

Arun-Baskaran commented Apr 26, 2017

I'm new to python, could you explain me how to use paramiko / Pexpect in python ?

@snagacarl

This comment has been minimized.

Copy link

snagacarl commented Apr 19, 2018

If someone happens here because they are using Fabric: env.use_ssh_config = True

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.