Saturday, July 18, 2015

Linux sed comand to remove entries in authorized.keys file

I do a lot of scripting, coding and installation with various Linux distributions.  Entering passwords using the ssh command from a command line slows me down so I set up passwordless-ssh with encryption keys.  I don't plan to discuss how to create and use encryption keys in Linux for use with ssh because you can find a wealth of examples from a simple Google search.  

What I will show in this post is a simple Linux command to remove an entry in the .ssh/authorized_keys file on a target host.  The authorized_keys file contains the public keys of all the hosts who are allowed to log into the host without using a password.  This assumes you have set up your sshd server properly on the host.
I am sure I am not the only person who re-installs their Linux workstation/server when a new version of a distribution comes along (or I switch to an entirely different distribution because I think I like it more, I always come back to Fedora).  Unless I save my .ssh directory (which I might want to think about doing), I loose my passwordless-ssh capability to other servers.  The reason, I get a new public key and that does not match the remote authorized_keys file.   I have a script that will add my public key to a remote userid but I do not delete an existing key if it exists (just a safety factor I think).  Anyway, I normally go onto the remote host with my userid and manually edit .ssh/authorized_hosts and delete my public key for my workstation.  This can be a bit of a pain so I finally spent the time and located the following sed command that deletes ALL public keys for my workstation from a .ssh/authorized_keys file:

sed -i -e '/redacer/{N;d}' .ssh/authorized_keys

The string 'redacer' is the name of the public key I want to delete.  There can be multiple copies of the same key or a different key for a given host.  The command above will remove all copies.  Please note that this will update the file in-place so if you don't trust the command, you might want to remove the -i option and pipe it to a another file as follows:

sed  -e '/redacer/{N;d}' > akeys.txt

I found this command on the Unix.Stackexchange site so here is a reference to the place I learned about this command.  Another note: I think this will work on Linux and not necessarily on all Unix OS's.

No comments: