Charlton Roberts

Creative Developer, Squarespace

“Machinery has been taught arithmetic instead of poetry.”
Charles Babbage, 1832

Quick Way to Remove a Single Line from a File From the Command Line, Linux / Mac

The Problem

Our stack typically requires recreating our staging servers a lot. By default, Mac OSX throws a security error if the IP address of the computer that you are trying to log into leads to a different computer than the last time you logged in. Something like this:

````bash

ssh root@staging @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @ 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 83:48:94:b9:ce:53:34:xx:xx:xx:xx:xx:xx:xx:xx:xx. Please contact your system administrator. Add correct host key in /Users/croberts1/.ssh/knownhosts to get rid of this message. Offending RSA key in /Users/croberts/.ssh/knownhosts:15 RSA host key for ec2-xx-xx-xx-xx.compute-1.amazonaws.com has changed and you have requested strict checking. Host key verification failed. ```

I'm sure there is a better way to solve the solution, but my quickfix is to delete the line in the known_hosts file and re-authenticate the server. So I wondered if there was an easy way to do this, in a single line, from the command line.

The Solution

The key piece of information is the line of the offending entry. Which is:

/Users/croberts/.ssh/known_hosts:15

So we know we want to delete the 15th line using sed, then send the output to the original file. Of course, you'll usually have to sudo this as well.

>> sed '15d' /Users/croberts/.ssh/known_hosts > /Users/croberts/.ssh/known_hosts

Where 15 is the line number you want to delete.