unix

Automatically remove last machine sshed to from known_hosts file

If you ssh to machines that get reprovisioned often you get the familiar ssh warning:

@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@ WARNING: REMOTE HOST IDENTIFICATION HAS CHANGED! @
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
IT IS POSSIBLE THAT SOMEONE IS DOING SOMETHING NASTY!

You can use ssh-keygen -R $hostname to remove it from your known_hosts file. Thanks to Evan McNabb for that one. He suggested aliasing 'dk' for "delete key" into your ~/.bashrc like so:

alias dk='ssh-keygen -R '

which works well, but you have to copy paste the hostname you just sshed to after 'dk'. The other day I figured out a way to automate 'dk' into removing the system by pulling the hostname from bash history. You can put this in your .bashrc:

function dk() {
ssh-keygen -R $(history 2 | head -n 1 | awk '{print $3}' | sed 's/.*@//')
}

Since I'm learning bash more extensively and for others that don't already know what it does: it uses bash command substitution like '$(echo hi)' to first run the history command and show the last two commands run (the ssh and history commands) and then head is used to only print the first line, awk is used to print the third column, the user@hostname part and then sed is used to replace any username@ with nothing, then that hostname is given to ssh-keygen -R.

Syndicate content