Remove changed host key in inteligent way

Do not know for you folks, but I personally going mad every time than i see the next Warning:

root@pavlin:/# ssh root@172.0.0.1

@ 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 the RSA host key has just been changed.
The fingerprint for the RSA key sent by the remote host is
fe:08:d7:12:ce:f1:5e:bb:76:3b:88:0a:g7:57:c7:00.
Please contact your system administrator.
Add correct host key in /home/pavlin/.ssh/known_hosts to get rid of this message.
Offending key in /home/pavlin/.ssh/known_hosts:197
RSA host key for 172.0.0.1 has changed and you have requested strict checking.
Host key verification failed.

In fact, this message is trying to convince me that 02:43 AM in the morning, someone is suddenly substituted remote machine with another one … and that I should get contact with me is to solve the problem – AND I HATE THAT !

Normaly it’s happening when you are trying to connect to the same IP, but the machine is different…and should be approached with caution in the case of logging to a remote machine that you administer…normaly it get mad after the second time i see this 🙂

I personaly solved this “problem” in my opinion in a very elegant way…certainly using a shell script:

first go to your home folder..let say /home/pavlin

and then create file with user-friendly name of your choice for example “delk” <- from “delete key”

cd /home/pavlin/ && touch delk

then we put some logic in script:

#!/bin/bash
AM=`whoami`

if [ $AM == “root” ]
then
sed -e “$1″d /root/.ssh/known_hosts -i
else
sed -e “$1″d /home/$AM/.ssh/known_hosts -i
fi

logic use well know shell tools “sed” and “whoami” to determine and remove specific line from know_hosts file.

for example:

delk 197

It must and shall delete line 197, which contain key changes.

so…let make it executable…this time we will use root user so change to it.

chmod +x delk

and make it accessible by your own user

chown pavlin:pavlin delk

then put it to /bin/ dir.

mv delk /bin/

That’s it !

Now all you have to do is remember the number of the row containing the key in my case that will be: 197
so i put it like a parameter in my new command like that:


delk 197

and try again to login


root@pavlin:/# ssh root@172.0.0.1

and this time i get:


The authenticity of host '172.0.0.1 (172.0.0.1)' can't be established.
RSA key fingerprint is ff:07:c9:13:ce:f0:5e:dd:76:3b:88:0a:d5:57:c7:00.
Are you sure you want to continue connecting (yes/no)?

Hit “yes” and do your work.

Enjoy.