An easier, quicker way to edit the known_hosts file when an SSH server changes its host key
If you SSH to servers that change a lot (they’re hosted at Amazon Web Services, for instance), you may see this warning when you try to connect1:
The host key has changed because the server has changed, & I need to fix this so I can connect. The important line is this one:
That tells me that line 1602 of the known_hosts
file is the problem. If you open that file up (& it’s always located at ~/.ssh/known_hosts
), you’ll see line after line that looks like this:
Each of those has the IP address of the server along with the key for that server. In this case, line 160 has the problematic host key for the server I was trying to connect to, so I’m supposed to delete that line, save the known_hosts
file, and try to SSH to it again. When I do that, I’ll see this:
I enter yes
& this then appears:
And now I can SSH to that server again without any warnings, since the correct host key is now in known_hosts
.
However, I got lazy the other day & wrote a little function to make the process of deleting the line from known_hosts
a bit easier.
To use it, do this:
- Copy it into your
~/.bash_aliases
file (or your~/.profile
if you don’t use.bash_aliases
) - Source the
.bash_aliases
file by entering this & pressing Enter:source ~/.bash_aliases
- When you want to delete a line from
known_hosts
, enterknownhosts
followed by the line number. So, for instance, if line 6 is a problem, you’d delete it like this:
You could then immediately try again to connect to the SSH server. You’ll be prompted to accept the new key, & then you’re golden.
The name of the function is knownhosts
, without the underscore. If you want to call it something else, be my guest. Here’s what each part does:
-
cp ~/.ssh/known_hosts ~/.ssh/known_hosts_$(date +%Y%m%d-%H%M%S)
Make a backup of the existingknown_hosts
file just in case. The backup will have today’s date & the current time appended to it, giving it a name like this:known_hosts_20120406-175028
. -
sed -e "$1d" ~/.ssh/known_hosts > ~/.ssh/known_hosts_new
Usesed
to delete the line you passed to the function via the command line (that comes in from the$1
). Normally you delete lines withsed
by enteringsed -e "8d" file
, which would delete line 8 from the file.$1
is a variable that takes the number right afterknownhosts
and inserts that instead.Normally
sed
writes to STDOUT, but instead we want to redirect it to another file, which in this case is~/.ssh/known_hosts_new
. -
mv ~/.ssh/known_hosts_new ~/.ssh/known_hosts
Overwrite the oldknown_hosts
with the newknown_hosts
. -
chmod 644 ~/.ssh/known_hosts
Set the correct permissions on theknown_hosts
file.
That’s it. I hope it’s helpful. This little function has helped me be even more lazy, & that’s always a good thing.