Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Paramiko example using private key
import paramiko
k = paramiko.RSAKey.from_private_key_file("/Users/whatever/Downloads/mykey.pem")
c = paramiko.SSHClient()
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
print "connecting"
c.connect( hostname = "www.acme.com", username = "ubuntu", pkey = k )
print "connected"
commands = [ "/home/ubuntu/firstscript.sh", "/home/ubuntu/secondscript.sh" ]
for command in commands:
print "Executing {}".format( command )
stdin , stdout, stderr = c.exec_command(command)
print stdout.read()
print( "Errors")
print stderr.read()
c.close()
@zackster

This comment has been minimized.

Copy link

@zackster zackster commented Apr 23, 2014

Thanks.

@Ghost0817

This comment has been minimized.

Copy link

@Ghost0817 Ghost0817 commented Apr 13, 2015

not working
resulted error is "paramiko.ssh_exception.SSHException: not a valid RSA private key file"

there is my file data
---- BEGIN SSH2 PUBLIC KEY ----
Comment: "rsa-key-20111127"
AAAAB3NzaC1yc2EAAAABJQAAAIEAqAxgtgyVlblABlabLa
---- END SSH2 PUBLIC KEY ----

@sprive

This comment has been minimized.

Copy link

@sprive sprive commented May 19, 2015

@Ghost0807 - Unclear why your key is not working.
Did you try generating another key, as a test?
(even if your existing key "works with other software", this is a good test to gather information. )

The example worked perfectly for me, under Linux

@christophfink

This comment has been minimized.

Copy link

@christophfink christophfink commented Jun 25, 2015

@Ghost0817: your file contains the public key, not the private one …

@subodhp

This comment has been minimized.

Copy link

@subodhp subodhp commented Mar 8, 2016

Hi,

This is awesome. Just a correction around the "print "Executing {}".format( command )" statement.
It needs {0} to work under Python3.

Thanks,
Subodh Pachghare
www.thesubodh.com

@seaweasel

This comment has been minimized.

Copy link

@seaweasel seaweasel commented Apr 27, 2016

A blessing on your house.

@hustcc

This comment has been minimized.

Copy link

@hustcc hustcc commented Aug 1, 2016

I genarate a key with ssh-keygen -t rsa, but can not connect.

Traceback (most recent call last):
  File "E:\Eclipse_WS\PyTest\src\ssh\ssh.py", line 23, in <module>
    s.connect(ip, port, username, key_filename='C:/Users/hustcc/.ssh/id_rsa.pub')
  File "D:\Python27\lib\site-packages\paramiko\client.py", line 367, in connect
    look_for_keys, gss_auth, gss_kex, gss_deleg_creds, gss_host)
  File "D:\Python27\lib\site-packages\paramiko\client.py", line 584, in _auth
    raise saved_exception
paramiko.ssh_exception.AuthenticationException: Authentication failed.
@bandarji

This comment has been minimized.

Copy link

@bandarji bandarji commented Sep 20, 2016

@hustcc - use id_rsa, not id_rsa.pub

The client uses a private key, not a public one.

@DamirPorobic

This comment has been minimized.

Copy link

@DamirPorobic DamirPorobic commented Jan 3, 2017

Just a note, if you have generated your keys via puttygen and they are in ppk format, it's not going to work, go back to puttygen, load you ppk key and export it as OpenSSH (Conversion -> Export OpenSSH Key)

@zioalex

This comment has been minimized.

Copy link

@zioalex zioalex commented Jan 6, 2017

Thanks it works like a charm!

@crisrol13

This comment has been minimized.

Copy link

@crisrol13 crisrol13 commented Mar 17, 2017

Hi, how can I fix this?
ImportError: DLL load failed: %1 is not a valid Win32 application.

@sanudavis

This comment has been minimized.

Copy link

@sanudavis sanudavis commented May 23, 2017

it worked for me thanks i converted ppk file to OpenSSH key using keygen and it works. Only one note I have for IPV6 address we have to mention the ethernet Interface number following the ipv6 address like "ipv6_address + %ethernet_Interface_Number" for ex. "fe80::217:88ff:fe0d:d1d0%25"

@c0rv00

This comment has been minimized.

Copy link

@c0rv00 c0rv00 commented May 27, 2017

Thanks for example, i try to run this code , i generate key with keygen and export it as OpenSSH key. Private key in the same path of script ... then i copied public key in .ssh in my linux distro and renamed to authorized_key but error occors ....
paramiko.ssh_exception.AuthenticationException: Authentication failed.
The exact procedure for connecting to a ssh server with key are: ??

@c0rv00

This comment has been minimized.

Copy link

@c0rv00 c0rv00 commented May 27, 2017

ok i have solution.

  1. create key ssh2 2048 with puttygen
  2. copy public key in a file named authorized_key in .ssh home dir of your server ssh linux with chmod 600
  3. chmod 700 .ssh dir in home dir
  4. change config file uncomment AuthorizedKeysFile
  5. in the same folder of python script put private key generated by puttygen exported as OpenSSH key
    well done.
    tnx
@arjunbhoot

This comment has been minimized.

Copy link

@arjunbhoot arjunbhoot commented Sep 1, 2017

I'm getting an error while using this example,

not a valid RSA private key file
The error comes from paramiko.RSAKey.from_private_key_file("/Users/whatever/Downloads/mykey.pem") here.
I've .ppk file for authentication.
This key is working well with FileZilla but while using this example it giving me an error, anyone has a solution for this problem?

@ahaw021

This comment has been minimized.

Copy link

@ahaw021 ahaw021 commented Oct 1, 2017

export the PPK file to a PEM format

@gurolcay

This comment has been minimized.

Copy link

@gurolcay gurolcay commented Oct 13, 2017

I can't understand how works this code. I do this steps:

  • run ssh-keygen -t rsa in server
  • and then I copy the host's id_rsa to any txt file on the client(my computer)
  • and then run this code(paramiko_example.py)

But I get error message which is

paramiko.ssh_exception.AuthenticationException: Authentication failed.

What is the thing I'm missing?

@AymanEG

This comment has been minimized.

Copy link

@AymanEG AymanEG commented Oct 27, 2017

Hello guys,

I am facing the same issue like @arjunbhoot. I have a working ppk file via putty and filezilla. I tried to puttygen -> Conversions -> Export Open SSH Key and named the file as .pem but does not work. any ideas ?! last version paramiko , python 3.6

@c0paten

This comment has been minimized.

Copy link

@c0paten c0paten commented Jan 6, 2018

Works for me pretty nicely!

"Just a note, if you have generated your keys via puttygen and they are in ppk format, it's not going to work, go back to puttygen, load you ppk key and export it as OpenSSH (Conversion -> Export OpenSSH Key) and save it with .pem file."

@techwav

This comment has been minimized.

Copy link

@techwav techwav commented Jan 24, 2018

:\python27\lib\site-packages\paramiko\client.pyc in _auth(self, username, password, pkey, key_filenames, allow_agent, look_for_keys, gss_auth, gss_kex, gss_deleg_creds, gss_host, passphrase)
712 # if we got an auth-failed exception earlier, re-raise it
713 if saved_exception is not None:
--> 714 raise saved_exception
715 raise SSHException('No authentication methods available')
716

AuthenticationException: Authentication failed.

@srilatha54

This comment has been minimized.

Copy link

@srilatha54 srilatha54 commented Feb 28, 2018

Hai guys,
I am having a issue with connecting to the remote server .

import StringIO
import paramiko
ssh=paramiko.SSHclient()
f='C:\USers\Documents\private.ppk'
f=StringIO.StringIO(f)
mykey=Paramiko.RSAKey.from_private_key_file(f)
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(198.168.2.1,root,pkey=mykey)
print"conneced "
ERROR:
COERCING TO UNICODE :need string or buffer , instance found

if any one know the reason let me know

@alexanderfournier

This comment has been minimized.

Copy link

@alexanderfournier alexanderfournier commented Mar 28, 2018

@arjunbhoot did you ever resolve this?

@alexanderfournier

This comment has been minimized.

Copy link

@alexanderfournier alexanderfournier commented Mar 28, 2018

@AymanEG figure this out?

@byung-u

This comment has been minimized.

Copy link

@byung-u byung-u commented Jun 19, 2018

Thank you, sir.

@mhemeryck

This comment has been minimized.

Copy link

@mhemeryck mhemeryck commented Jan 16, 2019

worked for me, after generating the key file in PEM format:

ssh-keygen -m pem -t rsa -C "test"

The new default format provided by ssh-keygen is still not supported apparently; see paramiko/paramiko#618

@iv8

This comment has been minimized.

Copy link

@iv8 iv8 commented Feb 28, 2019

Thanks

@Mortimrr

This comment has been minimized.

Copy link

@Mortimrr Mortimrr commented Aug 1, 2019

error: raise TypeError("Expected unicode or bytes, got {!r}".format(s))
TypeError: Expected unicode or bytes, got <paramiko.rsakey.RSAKey object at 0x000002909C542D30>

use pythn3.7 and lasted paramiko.
Can someone help me?

@kartikgvv

This comment has been minimized.

Copy link

@kartikgvv kartikgvv commented Oct 5, 2019

not working
resulted error is "paramiko.ssh_exception.SSHException: not a valid RSA private key file"

there is my file data
---- BEGIN SSH2 PUBLIC KEY ----
Comment: "rsa-key-20111127"
AAAAB3NzaC1yc2EAAAABJQAAAIEAqAxgtgyVlblABlabLa
---- END SSH2 PUBLIC KEY ----

Please dont share any kind of keys although shown in comments

@ThaRising

This comment has been minimized.

Copy link

@ThaRising ThaRising commented Oct 16, 2019

Thank you so much for providing this example!

@darshanpatil94

This comment has been minimized.

Copy link

@darshanpatil94 darshanpatil94 commented Nov 5, 2019

I found this link useful: https://adamdehaven.com/blog/how-to-generate-an-ssh-key-and-add-your-public-key-to-the-server-for-authentication/
Added the key id_rsa to ssh-agent, and
In python code: ssh.connect(hostname, username=myuser, look_for_keys=True, allow_agent=True)
got rid of this errror. hope this helps.

@megustador

This comment has been minimized.

Copy link

@megustador megustador commented Feb 5, 2020

update paramiko to latest version and then it will work even with you new OPENSSH key format

@jasonsychau

This comment has been minimized.

Copy link

@jasonsychau jasonsychau commented May 8, 2020

@alexanderfournier make ssh key on computer, authorise on server, use key in program

@iamrahulgupta7

This comment has been minimized.

Copy link

@iamrahulgupta7 iamrahulgupta7 commented May 14, 2020

Error:

File "/usr/lib/python3.6/site-packages/paramiko/pkey.py", line 289, in _read_private_key
raise SSHException("not a valid " + tag + " private key file")
paramiko.ssh_exception.SSHException: not a valid RSA private key file

it worked for me when I created key with type RSA

ssh-keygen -m pem -t rsa

moreover in python3.8 print statement will not work the way it is mentioned above. Also changed from read to readlines and created a loop

xlist = (stdout.readlines())
for i in xlist:
print(i)
print("++++++++++++++++")

Nothing else need to be changed.

@StefanoGITA

This comment has been minimized.

Copy link

@StefanoGITA StefanoGITA commented May 17, 2020

Just a note, if you have generated your keys via puttygen and they are in ppk format, it's not going to work, go back to puttygen, load you ppk key and export it as OpenSSH (Conversion -> Export OpenSSH Key)

Hi, I've converted the file to OpenSSH (with puttygen)
but now if I use pkey = pk.RSAKey.from_private_key_file(key_filename)
On the connect I got

Authentication failed

If I use the filename
ssh.connect(hostname=ip_server, username=username, key_filename=key_filename)
I got

 raise ValueError("q must be exactly 160, 224, or 256 bits long")

ValueError: q must be exactly 160, 224, or 256 bits long

@sarthak405

This comment has been minimized.

Copy link

@sarthak405 sarthak405 commented Aug 19, 2020

Just a note, if you have generated your keys via puttygen and they are in ppk format, it's not going to work, go back to puttygen, load you ppk key and export it as OpenSSH (Conversion -> Export OpenSSH Key)

Worked perfectly for me. Thanks a lot!

@Amanjain98

This comment has been minimized.

Copy link

@Amanjain98 Amanjain98 commented Dec 15, 2020

Not working for me

Traceback (most recent call last):
File "/opt/cms/scripts/bam_sdrtrace.py", line 227, in
transfer_file1()
File "/opt/cms/scripts/bam_sdrtrace.py", line 148, in transfer_file1
k = paramiko.RSAKey.from_private_key_file("/home/esbc/.ssh/authorized_keys")
File "/usr/lib/python2.7/site-packages/paramiko/pkey.py", line 196, in from_private_key_file
key = cls(filename=filename, password=password)
File "/usr/lib/python2.7/site-packages/paramiko/rsakey.py", line 45, in init
self._from_private_key_file(filename, password)
File "/usr/lib/python2.7/site-packages/paramiko/rsakey.py", line 163, in _from_private_key_file
data = self._read_private_key_file('RSA', filename, password)
File "/usr/lib/python2.7/site-packages/paramiko/pkey.py", line 268, in _read_private_key_file
data = self._read_private_key(tag, f, password)
File "/usr/lib/python2.7/site-packages/paramiko/pkey.py", line 277, in _read_private_key
raise SSHException('not a valid ' + tag + ' private key file')
paramiko.ssh_exception.SSHException: not a valid RSA private key file

@anilmhaske1991

This comment has been minimized.

Copy link

@anilmhaske1991 anilmhaske1991 commented Mar 1, 2021

socket.py", line 918, in getaddrinfo for res in _socket.getaddrinfo(host, port, family, type, proto, flags):
socket.gaierror: [Errno 11001] getaddrinfo failed
what's wrong

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment