Delete a Line from a File by Its Line Number

I keep having this problem. You know how ssh will tell you when the host’s keys have changed? For example, you try to ssh to example.org

$ ssh example.org

and you get

@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@ 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
ff:ff:ff:ff:ff:ff:ff:ff:ff:ff:ff:ff:ff:ff:ff:ff.
Please contact your system administrator.
Add correct host key in /home/me/.ssh/known_hosts to get rid of this message.
Offending key in /home/me/.ssh/known_hosts:16
RSA host key for example.org has changed and you have requested strict checking.
Host key verification failed.

Well, you can

$ ssh-keygen -R example.org

But that doesn’t fix it completely. Try to connect again, and you may get something like

Warning: the ECDSA host key for 'example.org' differs from the key for the IP address '192.168.0.1'
Offending key for IP in /home/me/.ssh/known_hosts:17
Matching host key in /home/me/.ssh/known_hosts:19
Are you sure you want to continue connecting (yes/no)?

Dammit! I used to open this in a text editor and delete the offending line. But let’s think about this. It gives us the line number, and it’s a Unix system. Can’t we automate this?

Yep. Use sed. The offending line is 17? All we have to do is

$ sed -i 17d ~/.ssh/known_hosts

So sed edits the file in-line (-i), and deletes the 17th line (17d). Hooray!

This entry was posted in fixes and tagged , , , , , . Bookmark the permalink.

2 Responses to Delete a Line from a File by Its Line Number

  1. Alex says:

    Actually, the easier way is to do this: ssh-keygen -R 192.168.0.1

    —Alex

    • force says:

      Do you mean that supplying the IP address instead of the host or domain name fixes this? I will give that a try the next time it comes up. Thanks!

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>