ssh – remove offending key.

Whenever a system/server is re-installed or the host key changed for any reason, you would have seen the “host key verification failed”. And as usual you would have to go to known_hosts file and delete the offending key. I will show you 2 simple ways to do this here.

The output that you get in such scenario is:

Offending ECDSA key in ~/.ssh/known_hosts:4

First, you can use sed to directly delete the offending key with a command like this :

sed -i 4d ~/.ssh/known_hosts

So, if you see, we are using “-i” to do the changes inline and using “4d” command to delete the 4th line.

But being on Linux has the advantage that everything can be automated. So, lets do this in simpler way.

We will be using command called xclip for this, so get that intalled.

sudo dnf install xclip

Once that is done, add a alias in your bashrc file like this:

alias ssh-remove-key='a=( $(xclip -o|sed "s,:, ,") ) ; sed -i -e "${a[1]}d" ${a[0]}'

After this is done, whenever you get that error, copy the “<file>:line” portion and execute “ssh-remove-key” and the key is gone from file 🙂

Executing commands on multiple hosts

If you have to execute the same command in multiple hosts, then you can use mussh:

Description : Mussh is a shell script that allows you to execute a command or script
: over ssh on multiple hosts with one command. When possible mussh will use
: ssh-agent and RSA/DSA keys to minimize the need to enter your password
: more than once.

First install mussh with the following command

dnf install mussh

Now to run this for multiple hosts, you can run like this

mussh -h vm{1..2} -c "hostname"

This will run the commands on hosts – vm1 and vm3
Command that will be run is “hostname”
Similarly you can run other commands as well on multiple machines.

ssh authorized keys – limit ssh session to custom command

If you want a ssh key to be able to run a custom command only and nothing beyond that, then you can use the “command” option in the authorized_keys file of ssh.

 

For example, to limit user to run only top command with a key, you can add the key like this:

 

echo 'command="/usr/bin/top" ssh-rsa ' >>~/.ssh/authorized_keys