Remove Invalid Host Key from known_hosts in Ubuntu

When connecting to a remote server via SSH on Ubuntu, you might encounter a “Host key verification failed” error because the server’s host key has changed or become invalid. This quick guide explains how to resolve this issue by safely removing the problematic host key from your local known_hosts file using the terminal.

The safest and most efficient way to remove a changed host key is by using the built-in ssh-keygen utility. This command automatically searches your known_hosts file, removes the specified host, and creates a backup of the original file.

Run the following command in your terminal, replacing hostname-or-ip with the domain name or IP address of the remote server:

ssh-keygen -R hostname-or-ip

For example, if the server IP is 192.168.1.50:

ssh-keygen -R 192.168.1.50

If the remote server uses a custom SSH port, you must specify the host and port number enclosed in brackets:

ssh-keygen -R [192.168.1.50]:2222

Method 2: Manually Editing the known_hosts File

If you prefer to remove the line manually, you can edit the file using a text editor like Nano. The SSH warning message usually tells you the exact line number where the conflict exists (for example: Offending ECDSA key in /home/username/.ssh/known_hosts:12).

  1. Open the known_hosts file in your terminal:

    nano ~/.ssh/known_hosts
  2. Navigate to the line number indicated in the SSH error message.

  3. Delete the entire line containing the old host key.

  4. Save the file and exit Nano by pressing Ctrl + O, hitting Enter, and then pressing Ctrl + X.

Verifying and Reconnecting

Once the old key is removed, initiate the SSH connection again:

ssh username@192.168.1.50

SSH will prompt you to confirm the authenticity of the host. Type yes and press Enter to save the new host key to your known_hosts file and establish the connection.