Every once in a while a want to get rid on a line from a file called ~/.ssh/known_hosts and it happens that I even know the exact line number which I want to remove.

Thanks to sed this can be done on the command line in an easy step:

# Remove line 2 from the known hosts file
sed -i.old -e '2d' ~/.ssh/known_hosts

# Or if you don't want to keep a backup around
sed -i -e '2d' ~/.ssh/known_hosts

Use case

My typical use case is to remove an offending key from the file ~/.ssh/known_hosts, e.g. when I replaced a VM and I am just sure that the old entry should be wiped.

I think that's better than wiping the whole file and blindly accepting all hosts again.

Typically after changing one of my VMs, I'll see a message like the following:

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

A few lines below it contains the details of the offending key and gives the line number, so I think typing in the little sed based snippet is nearly as convenient as wiping the whole file and it leaves the other keys in place which prevents me from getting lazy in accepting unknown host keys.


Comments

comments powered by Disqus