Search code examples
pythonsshparamiko

SSH connection - hostkey


I'm trying to make a connection vis SSH using this code

#SSH conde for connection
ssh = paramiko.SSHClient()
# Load SSH host keys.
ssh.load_system_host_keys()
# Add SSH host key automatically if needed.
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(IP, username=USER, password=PSW,look_for_keys=False)

but somethimes a message like the one in the picture occurrs:

SSH_Question

that gives me the error shown in picture: Hostkey_Error

is there a way to avoid this message?


Solution

  • BadHostKeyException means that the SSH server's host key has changed, i.e. is different than the one you have stored (by default in ~/.ssh/known_hosts).

    Assuming you understand that this is bad practice in general (because you'll blindly accept host keys without verifying them), you can bypass host key verification by removing load_system_host_keys() and keeping AutoAddPolicy.

    The reason it's not working for you is because AutoAddPolicy automatically adds host keys of new hosts, but since load_system_host_keys() is used the host you're connecting to is considered known (albeit with a changed key, hence the exception).