Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

Is there a command (or a one-liner) to remove a ssh key on a server? Something like the opposite of ssh-copy-id?

share|improve this question
Some SSH server software support the RFC 4819 protocol for managing authorized SSH keys, but it's so rare it's almost nonexistent on Linux :( – grawity May 29 '12 at 7:38
Excellent question, this is really missing functionality to ssh-copy-id to facilitate key rotation. – Zabuzzman Mar 27 '15 at 22:33
up vote 5 down vote accepted

As Ignatio suggested this can be done with grep -v.

Here is a example which removes the key containing some unique string or just deletes the authorized_keys file when no other key remains.

if test -f $HOME/.ssh/authorized_keys; then
  if grep -v "some unique string" $HOME/.ssh/authorized_keys > $HOME/.ssh/tmp; then
    cat $HOME/.ssh/tmp > $HOME/.ssh/authorized_keys && rm $HOME/.ssh/tmp;
    rm $HOME/.ssh/authorized_keys && rm $HOME/.ssh/tmp;

Replace some unique string with something that only exists in the key you wish to remove.

As a oneliner over ssh this becomes

ssh hostname 'if test -f $HOME/.ssh/authorized_keys; then if grep -v "some unique string" $HOME/.ssh/authorized_keys > $HOME/.ssh/tmp; then cat $HOME/.ssh/tmp > $HOME/.ssh/authorized_keys && rm $HOME/.ssh/tmp; else rm $HOME/.ssh/authorized_keys && rm $HOME/.ssh/tmp; fi; fi'

Tested on Linux (SLES) and HP-UX.

share|improve this answer

sed provides a compact solution:

sed -i.bak '/REGEX_MATCHING_KEY/d' ~/.ssh/authorized_keys

This will save the original authorized_keys in authorized_keys.bak. If you don't want the backup then just change -i.bak to -i.

You can even remove multiple keys:

sed -i.bak '/REGEX1/d; /REGEX2/d' ~/.ssh/authorized_keys

The only tricky bit here is special characters in the regex need to be escaped.

share|improve this answer

Start with locking the accounts, for example :

passwd -l userName
passwd -l vivek

Then deleating is simple

rm -rf /home/vivek/.ssh
share|improve this answer
I don't think removing .ssh entirely is a good idea. – slhck May 29 '12 at 9:31
Nor locking the account itself... – grawity May 29 '12 at 14:36

Nope. You'll need to SSH in and use sed or grep to remove the key from the file.

share|improve this answer
Thank you. I will keep the question open a little longer to see if someone also can provide a script that does the opposite of ssh-copy-id – grm May 30 '12 at 11:56
@grm : I'd suggest you keep the question open forever, or at least until a ssh-undo-copy-id is implemented ! ;-) – Max L. Jul 30 '15 at 18:28

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.