Skip to content

Instantly share code, notes, and snippets.

@batok
Created April 10, 2012 16:11
Show Gist options
  • Save batok/2352501 to your computer and use it in GitHub Desktop.
Save batok/2352501 to your computer and use it in GitHub Desktop.
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()
@arjunbhoot
Copy link

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
Copy link

ahaw021 commented Oct 1, 2017

export the PPK file to a PEM format

@gurolcay
Copy link

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
Copy link

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
Copy link

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
Copy link

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
Copy link

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
Copy link

@arjunbhoot did you ever resolve this?

@alexanderfournier
Copy link

alexanderfournier commented Mar 28, 2018

@AymanEG figure this out?

@byung-u
Copy link

byung-u commented Jun 19, 2018

Thank you, sir.

@mhemeryck
Copy link

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
Copy link

iv8 commented Feb 28, 2019

Thanks

@Mortimrr
Copy link

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
Copy link

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
Copy link

Thank you so much for providing this example!

@darshanpatil94
Copy link

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
Copy link

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

@jasonsychau
Copy link

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

@iamrahulgupta7
Copy link

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
Copy link

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
Copy link

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
Copy link

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
Copy link

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

@vickyvikas7988
Copy link

Not working for me, while use the key using ssh client it works

Traceback (most recent call last):
File "/Users/xx/code/compute-ops/scripts/launch_intance_benchmark.py", line 105, in
k = paramiko.RSAKey.from_private_key_file("/Users/xx/.ssh/id_rsa.pem")
File "/Users/xx/code/compute-ops/venv3/lib/python3.7/site-packages/paramiko/pkey.py", line 206, in from_private_key_file
key = cls(filename=filename, password=password)
File "/Users/xx/code/compute-ops/venv3/lib/python3.7/site-packages/paramiko/rsakey.py", line 48, in init
self._from_private_key_file(filename, password)
File "/Users/xx/code/compute-ops/venv3/lib/python3.7/site-packages/paramiko/rsakey.py", line 169, in _from_private_key_file
data = self._read_private_key_file('RSA', filename, password)
File "/Users/xx/code/compute-ops/venv3/lib/python3.7/site-packages/paramiko/pkey.py", line 279, in _read_private_key_file
data = self._read_private_key(tag, f, password)
File "/Users/xx/code/compute-ops/venv3/lib/python3.7/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

@vickyvikas7988
Copy link

Converting the key
resolves the error
ssh-keygen -p -m PEM -f ~/.ssh/id_rsa

@dovanpho
Copy link

dovanpho commented May 7, 2021

thanks.
if your private key is in .ppk, you need convert to .pem.

@rdiazg14
Copy link

I resolve this problem with version paramiko-2.10.4

@jyotsna-atrium
Copy link

I see this error:

ModuleNotFoundError: No module named 'paramiko'

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