Paramiko "Unknown Server"
The exception was raised because you are missing a host key, the rather cryptic "Unknown server" is the clue - since the exception was raised from missing_host_key
Try this instead:
import paramiko
paramiko.util.log_to_file('ssh.log') # sets up logging
client = paramiko.SSHClient()
client.load_system_host_keys()
client.connect('127.0.0.1', username=username, password=password)
stdin, stdout, stderr = client.exec_command('ls -l')
The correct way is either:
Call the
HostKeys.add
on the instance returned bySSHClient.get_host_keys
before calling theconnect
, passing it the trusted key.from base64 import decodebytes # ... keydata = b"""AAAAB3NzaC1yc2EAAAADAQAB...""" key = paramiko.RSAKey(data=decodebytes(keydata)) client.get_host_keys().add('example.com', 'ssh-rsa', key)
To see how to obtain the fingerprint for use in the code, see my answer to:
Verify host key with pysftp.If you know a fingerprint only, see:
Python - pysftp / paramiko - Verify host key using its fingerprintOr load the already cached hostkey (e.g. by the command-line
ssh
) usingclient.load_system_host_keys()
.Or you can at least cache the hostkey from the first attempt to make sure it does not change in the future.
For that use
SSHClient.load_host_keys
beforeconnect
. It makes Paramiko automatically add the new host key to the file (when combined withAutoAddPolicy
).
I encountered this issue and wanted to post a workaround here. The issue was indeed the ssh server sending ecdsa keys, which are not supported (yet) with paramiko. On my debian Wheezy system I disabled ecdsa by commenting out a single line in /etc/ssh/sshd_config:
# HostKey /etc/ssh/ssh_host_ecdsa_key
Restarted sshd, and it was back to using RSA. There were some ecdsa keys in my known_hosts file so I just deleted it to reset, and logged in manually to recreate the keys. From there, paramiko worked perfectly as expected, with RSA host key checking.
I experienced the same issue and here's the solution that worked out for me:
import paramiko
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect('127.0.0.1', username=username, password=password)
stdin, stdout, stderr = client.exec_command('ls -l')
This is to set the policy to use when connecting to a server that doesn't have a host key in either the system or local HostKeys objects. The default policy is to reject all unknown servers (using RejectPolicy). You may substitute AutoAddPolicy or write your own policy class.
More details at paramiko api doc. Hope this helps.
After that you can save into an other keyfile file for next usage as follows.
ssh.get_host_keys().save('/some/file/path')
You can always load from a file as follows.
ssh.load_host_keys('/some/file/path')