Command to remove a ssh authorized key on server
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.
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;
else
rm $HOME/.ssh/authorized_keys && rm $HOME/.ssh/tmp;
fi;
fi
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.
Nope. You'll need to SSH in and use sed
or grep
to remove the key from the file.