I would like to connect to an ssh server using an OpenSSH key passed to paramiko's .connect()
method.
The following code raises paramiko.ssh_exception.AuthenticationException: Authentication failed.
on .connect()
even though the key looks correct:
import paramiko
# the key below is shortened for readability, it is made of blocks ending with \\n - in other words
# the return-carriage in the original file was replaced with \\n
key = "-----BEGIN RSA PRIVATE KEY-----\\nMIIEpQIBA(...)b+iro=\\n-----END RSA PRIVATE KEY-----\\n"
# this is to dump the key for checking a command-line connection with that key
with open("key.priv", "w") as f:
f.write(key.replace('\\n', '\n'))
key = paramiko.PKey(data=key)
params = {
'hostname': '10.0.0.1',
'port': 22,
'username': 'root',
'look_for_keys': False,
'timeout': 5,
'pkey' : key
}
ssh = paramiko.SSHClient() # Initiate SSH client
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) # allow to add unknown ssh key
res = ssh.connect(**params)
Running the code:
Traceback (most recent call last):
File "C:/Users/aa/testsshkey.py", line 19, in <module>
res = ssh.connect(**params)
File "C:\Python27\lib\site-packages\paramiko\client.py", line 307, in connect
look_for_keys, gss_auth, gss_kex, gss_deleg_creds, gss_host)
File "C:\Python27\lib\site-packages\paramiko\client.py", line 519, in _auth
raise saved_exception
paramiko.ssh_exception.AuthenticationException: Authentication failed.
Process finished with exit code 1
I tried to have \\n
and well as \n
in key
, no changes (both are accepted by paramiko.PKey()
).
The code above also dumps the key to a file to test a command-line ssh connection, which succeeds:
host1$ chmod 600 key.priv
host1$ ssh root@10.0.0.1 -i key.priv
root@host2 #
Is there a specific format for the key to be passed to paramiko.PKey()
? Its docs claim that
Raises SSHException:
if a key cannot be created from the data or msg given, or no key was passed in.
which does not happen in my case (therefore I assume that the format of the key is acceptable Edit: I checked with a random string and the "key" is still accepted, so no checks are made on the correctness of the key)