SSH Login Error: Host key verification failed

This error message occurs under Linux and OS X when you try to log into a server via SSH where the RSA key has changed since the last login.

The reason behind the message is to prevent a man-in-the-middle attack so it’s shown for your own safety. Nevertheless, the error message can be annoying if you for example clean installed your server and now you can’t log in again.

The file ~/.ssh/known_hosts is is crucial here as it stores the public keys of the servers you already connected to via SSH. There are 3 ways to bypass the error message and connect to the server:

Option 1: Delete Known Hosts

By typing $ rm ~/.ssh/known_hosts the known hosts file will be deleted and you are able to connect again. This has the side effect that the keys from all other servers you were connected to are lost as well. So the next time you connect to a different server you have to confirm the dialog Are you sure you want to continue connecting (yes/no)? again. Also you won’t notice if another server uses a malicious key. Therefore I would recommend against using this option.

Option 2: SSH-Keygen

The command $ ssh-keygen -R hostname only deletes a single key from the known host file. In this case the one belonging to hostname. As this option is fast and simple I would recommend it.

Option 3: Deactivate Key Check

There is another very convenient option of disabling key checks altogether. Although this is not intended it still works with a trick:

ssh -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no

By issuing this command the location of the known hosts file is set to /dev/null. This means the file is always empty and there can be no wrong keys in it. By setting StrictHostKeyChecking=no the key is automatically added to the known hosts file without prompting the user. By using these two parameters the key check is effectively deactivated.

To avoid having to enter this line every time you can abbreviate the SSH command by adding an alias to the ~/.bash_profile or ~/.bashrc file:

alias ssh='ssh -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no'

This automatically disables the host key check each time you type $ ssh. It’s on you to decide if it’s worth disabling the check as it makes you vulnerable to man-in-the-middle attacks.