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.
Method 1:
Using the ssh-keygen Command (Recommended)
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-ipFor example, if the server IP is 192.168.1.50:
ssh-keygen -R 192.168.1.50If 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]:2222Method 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).
Open the
known_hostsfile in your terminal:nano ~/.ssh/known_hostsNavigate to the line number indicated in the SSH error message.
Delete the entire line containing the old host key.
Save the file and exit Nano by pressing
Ctrl + O, hittingEnter, and then pressingCtrl + X.
Verifying and Reconnecting
Once the old key is removed, initiate the SSH connection again:
ssh username@192.168.1.50SSH 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.