How to Update Hostkey Automatically in Known Hosts

In this Linux tutorial, you will learn how to update hostkey automatically in known hosts.

If you get below error when you try to take ssh access of Linux server.
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@ WARNING: REMOTE HOST IDENTIFICATION HAS CHANGED! @
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
IT IS POSSIBLE THAT SOMEONE IS DOING SOMETHING NASTY!
Someone could be eavesdropping on you right now (man-in-the-middle attack)!
It is also possible that a host key has just been changed.
The fingerprint for the RSA key sent by the remote host is
[…].
Please contact your system administrator.
Add correct host key in /home/Linux-user/.ssh/known_hosts to get rid of this message.
Offending RSA key in /home/Linux-user/.ssh/known_hosts:287
RSA host key for […] has changed and you have requested strict checking.
Host key verification failed.

This above message is normal, this kind message you will get when you have updated your ssh-key means new key doesn’t match the old one.

You can easily resolve ssh issue with simple step

Option 1: Just edit “~/.ssh/known_hosts“ or “/home/Linux-user/.ssh/known_hosts” and delete line 287
[OR] Option 2: Use ssh-keygen command to delete the invalid key

Eg: ssh-keygen -R “IP Address or your server hostname”

This method will tell ssh to update the host’s key which has changed and the new key needs to add/update.

R hostname
Removes the hostname keys from a known_hosts file. To delete hashed hosts this option is very useful (see the -H option above).

Assume you want to do the same thing for several servers then follow the below method:

Script to update/add/replace single host’s key in known_hosts

SOURCE_HOST=[hostname or IP]

# Remove the old key(s) from known_hosts
ssh-keygen -R $SOURCE_HOST

# Add the new host’s key(s) to known_hosts and hash the hostname or IP address
ssh-keyscan -H $SOURCE_HOST >> ~/.ssh/known_hosts

Script to update/add/replace multiple host’s key in known_hosts

for SOURCE_HOST in `more server-ip-address-list.txt`
do
# Remove the old key(s) from known_hosts
ssh-keygen -R $SOURCE_HOST

# Add the new host’s key(s) to known_hosts and hash the hostname or IP address
ssh-keyscan -H $SOURCE_HOST >> ~/.ssh/known_hosts
done

This is the end tutorial, you learned how to Update Hostkey Automatically in Known Hosts.


Thanks for reading this article, you’ll also like below articles.

Linux Blogs for beginner

AWS NAT Instance vs AWS Bastion Hosts

What is AWS RDS