[Django]-Paramiko SSH failing with "Server '…' not found in known_hosts" when run on web server

45👍

You can hard-code the host key in your Python code, using HostKeys.add:

import paramiko
from base64 import decodebytes

keydata = b"""AAAAB3NzaC1yc2EAAAABIwAAAQEA0hV..."""
key = paramiko.RSAKey(data=decodebytes(keydata))
 
client = paramiko.SSHClient()
client.get_host_keys().add('example.com', 'ssh-rsa', key)
client.connect(...)

Or, as you are connecting within a private network, you can give up on verifying host key altogether, using AutoAddPolicy:

client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect(...)

(This can be done only if you really do not need the connection to be secure)

0👍

In addition to Martin Prikryl answer, maybe you’re coding for a dynamic environment where you don’t know this information, then you could validate de host by yourself and then add to know_hosts file. This answer is oriented to sys admins.

Direct add:

$ ssh-keyscan sample.host.com >> ~/.ssh/known_hosts
o
$ ssh-keyscan 192.168.1.20 >> ~/.ssh/known_hosts

Need user input:

$ ssh sample.host.com
o
$ ssh 192.168.1.20

Keep in mind that you must have the correct credentials to successfully connect.

Leave a comment