Paramiko "Unknown Server"
I experienced the same issue and here's the solution that worked out for me:
import paramikoclient = 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.
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 paramikoparamiko.util.log_to_file('ssh.log') # sets up loggingclient = 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
).