Sometimes, I see the following error on ssh.
qiang@server34:~$ ssh <user>@<some_hostname>
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@ 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
SHA256:GdgZw/VvLqtuv4dUmNwAZitB4JRPCYn8pb+aDU5rKiQ.
Please contact your system administrator.
Add correct host key in /u/qiang/.ssh/known_hosts to get rid of this message.
Offending RSA key in /u/qiang/.ssh/known_hosts:1432
RSA host key for <some_hostname> has changed and you have requested strict checking.
Host key verification failed.
It’s ok because <some_hostname> was a virtual machine and its ip address was changed each time it was destroyed and re-created.
The outdated host key could be removed by this command:
sed -i '1432d' ~/.ssh/known_hosts
Still, it is tedious, and I am wondering if there could be a bash script automating the process: issue the ssh command to connect to the remote host, delete the outdated host key if ssh exited because of this error, and re-run the ssh command to connect.
I gave it a try, first to detect the error:
qiang@server04:~/bin$ cat sshw
#!/usr/bin/env bash
errormsg=$(ssh "$@" 2>&1 >/dev/null)
re="Offending RSA key"
if [[ $errormsg =~ $re ]]; then
echo "lalala"
fi
Problem is, the session was frozen after the password was typed at the prompt. Not sure what went wrong?