Use sed & Bash To Help With ssh Annoyance

ssh keeps track of the systems it is connected to, and is able to tell you if a particular system has changed. It is a security feature – informing you about the change of a fingerprint of the system you are connecting to.
If that change is unexpected, obviously you need to be careful, as it may be a man-in-the-middle attack.

It can be annoying however, as ssh sometimes decides that you not allowed to connect to that new system. It always disallows the log-in if you’re trying to use password authentication, to prevent giving it away to a potential attacker.

You are usually presented with few lines of text explaining that in such a situation, and that you can get into the system with expected fingerprint change by removing a certain line in known_hosts file, where the list of fingerprints is held.

You can do it via any test editor, like Vi, nano or emacs. But you need to find this specific line first. You can use sed to help you do that. For example, remove line 526 from user’s known_hosts file:

sed -i ’526d’ /home/user/.ssh/known_hosts

at that point most sysadmins would think about how to shortcut usage of this command. Bash provides a very useful mechanism to achieve that – namely aliases. You can assign a complicated or lengthy  command to an alias, which may be a lot shorter:

alias ll=’ls -l’

The nice thing is that aliases are substituted before running the command, so we can add further parts of the command at the end, and the following usage is possible:

ll /etc (equivalent to ls -l /etc)

However, our command has a line number in the middle, and aliases don’t work well with variables. You would have to use a system variable and redefine it everytime you were to use the alias – quite annoying!

Lucky for us, bash is rather advanced and allows you definition of functions. Functions can have variables:

function rm_fingerprint { eval sed ‘”$1″!d’ \ /home/user/.ssh/known_hosts; }

Running the command rm_fingerprint 526 will now substitute $1 variable with our line number and remove it – and the good thing is that you can add either alias or function definition to your .bashrc file, so it will be available to you the next time you log in.

This entry was posted in Managed Hosting. Bookmark the permalink.

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>