user3398900
user3398900

Reputation: 845

How to SSH from one system to another using python

I am trying to perform SSH from one system to another using paramiko in python

import paramiko
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(
paramiko.AutoAddPolicy())
ssh.connect('127.0.0.1', username='jesse', 
password='lol')

using this reference (http://jessenoller.com/blog/2009/02/05/ssh-programming-with-paramiko-completely-different )

This is the case when we know the password of the system you want to log-in BUT if i want to login to a system where my public-key is copied and i dont know the password. Is there a way to do this

Thanks in advance

Upvotes: 0

Views: 1140

Answers (3)

B 7
B 7

Reputation: 690

This code should work:

import paramiko

host = "<your-host>"

client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect(host, username='<your-username>', key_filename="/path/to/.ssh/id_rsa" , port=22)

# Just to test a command
stdin, stdout, stderr = client.exec_command('ls')
for line in stdout.readlines():
    print line

client.close()

Here is the documentation of SSHClient.connect()

EDIT : /path/to/.ssh/id_rsa is your private key!

Upvotes: 1

DeepSpace
DeepSpace

Reputation: 81594

SSHClient.connect accepts a kwarg key_filename, which is a path to the local private key file (or files, if given a list of paths). See the docs.

key_filename (str) – the filename, or list of filenames, of optional private key(s) to try for authentication

Usage:

ssh.connect('<hostname>', username='<username>', key_filename='<path/to/openssh-private-key-file>')

Upvotes: 4

danny
danny

Reputation: 5270

Adding the key to a configured SSH agent would make paramiko use it automatically with no changes to your code.

ssh-add <your private key>

Your code will work as is. Alternatively, the private key can be provided programmatically with

key = paramiko.RSAKey.from_private_key_file(<filename>)
SSHClient.connect(pkey=key)

Upvotes: 0

Related Questions