Search code examples
pythonsshrsaparamikoopenssh

Python-Parmiko Error: 'RSAKey' object is not iterable'


I created a RSA key pair via sudo ssh-keygen -t rsa -b 4096 and copied to the .ssh folder. I am using the Python paramiko package. My code is:

import paramiko
k = paramiko.RSAKey.from_private_key_file('/home/username/.ssh/id_rsa', password='mypassphrase')
s = paramiko.SSHClient()
s.set_missing_host_key_policy(paramiko.AutoAddPolicy())
conn = s.connect('remote_computer', username ='username', port=22, key_filename =k)
command = 'sudo python ~/pythonscript.py'
(stdin, stdout, stderr) = s.exec_command(command)
s.close()

But when I try to run the code, I am getting the following error and traceback:

Traceback (most recent call last):
File "pythonparamikoscript.py", line 6, in <module>
conn = s.connect('remote_computer', username ='username', port=22, key_filename =k)
File "/usr/lib/python2.7/dist-packages/paramiko/client.py", line 307, in connect
look_for_keys, gss_auth, gss_kex, gss_deleg_creds, gss_host)
File "/usr/lib/python2.7/dist-packages/paramiko/client.py", line 441, in _auth
for key_filename in key_filenames:
TypeError: 'RSAKey' object is not iterable

Help is appreciated, since this leaves me desperate.


Solution

  • connect() accepts different arguments:

    • pkey (PKey) which is the place where you should assign your key
    • key_filename (str) which is just a string with a location of your key.

    So running

    conn = s.connect('remote_computer', username ='username', port=22, pkey=k)
    

    should do the job.