Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to ssh connect through python Paramiko with ppk public key

i'm using Paramiko to connect through ssh to a server.

Basic authentication works well, but i can't understand how to connect with public key.

When i connect with putty, the server tell me this:

Using username "root". Authenticating with public key "[email protected]" Passphrase for key "[email protected]": [i've inserted the passphrase here] Last login: Mon Dec  5 09:25:18 2011 from ... 

I connect to it with this ppk file:

PuTTY-User-Key-File-2: ssh-rsa Encryption: aes256-cbc Comment: [email protected] Public-Lines: 4 [4 lines key] Private-Lines: 8 [8 lines key] Private-MAC: [hash] 

With basic auth the error i get (from the log) is:

DEB [20111205-09:48:44.328] thr=1   paramiko.transport: userauth is OK DEB [20111205-09:48:44.927] thr=1   paramiko.transport: Authentication type (password) not permitted. DEB [20111205-09:48:44.927] thr=1   paramiko.transport: Allowed methods: ['publickey', 'gssapi-with-mic'] 

I've tried to include that ppk file and set to auth_public_key, but didn't work.

Can you help me?

like image 758
apelliciari Avatar asked Dec 05 '11 08:12

apelliciari


People also ask

Can you SSH with public key?

Once your public key is added to your ~/. ssh/authorized_keys file on the remote system, the setup process is complete, and you should now be able to SSH to your account from the computer that has your private key.

How do I use Paramiko in Python?

A Paramiko SSH Example: Connect to Your Server Using a Password. This section shows you how to authenticate to a remote server with a username and password. To begin, create a new file named first_experiment.py and add the contents of the example file. Ensure that you update the file with your own Linode's details.


2 Answers

Ok @Adam and @Kimvais were right, Paramiko cannot parse .ppk files.

So the way to go (thanks to @JimB too) is to convert .ppk file to OpenSSH private key format; this can be achieved using PuTTYgen as described here.

Then it's very simple getting connected with it:

import paramiko ssh = paramiko.SSHClient()  ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())  ssh.connect('<hostname>', username='<username>', password='<password>', key_filename='<path/to/openssh-private-key-file>')  stdin, stdout, stderr = ssh.exec_command('ls') print stdout.readlines() ssh.close() 
like image 177
apelliciari Avatar answered Oct 09 '22 22:10

apelliciari


For me I doing this:

import paramiko hostname = 'my hostname or IP'  myuser   = 'the user to ssh connect' mySSHK   = '/path/to/sshkey.pub' sshcon   = paramiko.SSHClient()  # will create the object sshcon.set_missing_host_key_policy(paramiko.AutoAddPolicy()) # no known_hosts error sshcon.connect(hostname, username=myuser, key_filename=mySSHK) # no passwd needed 

works for me pretty ok

like image 24
Carlos M G T Avatar answered Oct 09 '22 23:10

Carlos M G T