Skip to content

Instantly share code, notes, and snippets.

@cearls
Forked from huyby/replace-ssh-key.md
Created November 28, 2016 16:29
Show Gist options
  • Save cearls/b3b71901755a1ceb1f974d7636be288d to your computer and use it in GitHub Desktop.
Save cearls/b3b71901755a1ceb1f974d7636be288d to your computer and use it in GitHub Desktop.
Replace or delete ssh key in authorized_key files

Test for replacement

sed -n 's#ssh-rsa.*OLD_KEY_ID#NEW_KEY# p' .ssh/authorized_keys

Test for deleting

sed -n '#ssh-rsa.*KEY_ID# p' .ssh/authorized_keys

Do replacement in multiple authorized_key files (change maxdepth to your needs)

sudo find . -maxdepth 3 -name "authorized_keys" -exec sed -i.old 's#ssh-rsa.*OLD_KEY_ID#NEW_KEY#' {} \;

Do delete in multiple authorized_key files (change maxdepth to your needs)

sudo find . -maxdepth 3 -name "authorized_keys" -exec sed -i.old '#ssh-rsa.*KEY_ID# D' {} \;

Tip: use a bash variable e.g. $NEW_KEY to use in your commands. Note that you'll need to use double instead of single quotes in the sed command.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment