Deleting line in file without vim

Whenever I move around machines and server hosts, it is not uncommon for me to encounter this problem:

calvin$ ssh root@my.ip.addr.ess
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
Please contact your system administrator.
Add correct host key in /Users/calvin/.ssh/known_hosts to get rid of this message.
Offending key in /Users/calvin/.ssh/known_hosts:64
RSA host key for my.ip.addr.ess has changed and you have requested strict checking.
Host key verification failed.

My usual approach would be to

vim ~/.ssh/known_hosts

, navigate to the offending line and remove it.

But here’s a faster way without needing to open up my vim.  sed to the rescue -

But guess what, it doesn’t work on Mac OSX.  If we attempt this, we will simply get:

calvin$ sed -i 64d ~/.ssh/known_hosts
sed: 1: "/Users/calvin/.ssh/know ...": command c expects \ followed by text

Apparently, the sed that comes by default on Mac OSX is the BSD-version (well, obviously).  It requires an option – the file suffix for a backup file – provided to it.   So,

calvin$ sed -i .bak '64 d' ~/.ssh/known_hosts

works perfectly; and generates a back up known_hosts.bak in the same directory containing line 64, while known_hosts file now has line 64 deleted as we wished.

Alternatively, we can grab a copy of GNU sed:-

calvin$ sudo port -v install gsed
---> Computing dependencies for gsed.
---> Cleaning gsed
---> Removing work directory for gsed
---> Scanning binaries for linking errors: 100.0%
---> No broken files found.
Calvins-MacBook-Pro.local ttys005 Fri Jul 13 16:07:10 |~|
calvin$ which sed
Calvins-MacBook-Pro.local ttys005 Fri Jul 13 16:07:15 |~|
calvin$ which gsed

And from now on, we can use gsed in a linux-conformant way. (i.e. `gsed -i ’64 d’ ~/.ssh/known_hosts` will work without an error)

  • stefantalpalaru

    Or you can just disable this type of check by setting  StrictHostKeyChecking to ‘no’ in your /etc/ssh/ssh_config

    • calvin

      Right! Thanks :-)

  • glenn

    You just made my day… you can’t believe how much you helped me with this post!!!!! Thanks a lot!!!!