Skip to content

Instantly share code, notes, and snippets.

@cdelorme
Last active May 3, 2023 12:30
Show Gist options
  • Save cdelorme/30d8ea33bfd287e74892 to your computer and use it in GitHub Desktop.
Save cdelorme/30d8ea33bfd287e74892 to your computer and use it in GitHub Desktop.
Automatically Update Remote Authorized Keys
I tend to break and rebuild my systems regularly. It has gotten to the point that I generally do not have an SSH key for over a year.
This has created a serious dilemma when it comes to maintaining access to remote systems. I usually disable normal password access on any servers I maintain, which means unless I have multiple systems that can access so I can replace the keys I could permanently loose access to those systems. In considering possible solutions I came up with one that has saved my bacon regularly.
First, I use my [dot-files](https://github.com/cdelorme/dot-files) repository after installing any new system. If that system is secure I will generate a new SSH key and load it into github via curl through their api.
On servers which I need to retain access, I create a simple bash script to poll my github accounts keys. I throw it into a user-local `~/.bin/update-keys` file, and make it executable.
Finally, I modify the crontab to execute this script regularly:
*/5 * * * * ~/.bin/update_keys
Depending on access needs I may try to execute it every 5 minutes, hourly, or daily. This approach has allowed me to change my keys regularly without destroying my own remote access privileges. It tends to be amazingly useful, and could be both simplified and further secured by replacing the entire `authorized_keys` file. However, I do not always have every one of my keys on my github account and would rather remove keys on my own time.
#!/bin/bash
keys=$(wget -qO- https://github.com/$(whoami).keys)
echo "$keys" | while read -r key
do
if [ -f "${HOME}/.ssh/authorized_keys" ] && ! grep "$key" "${HOME}/.ssh/authorized_keys" &> /dev/null
then
echo "$key" >> "${HOME}/.ssh/authorized_keys"
fi
done
@plexus
Copy link

plexus commented Jun 4, 2020

Thanks for sharing, I found this via google, and made a version that gets all keys for a given GH organization.

https://gist.github.com/797cf37ed7e7d67474af3765704e0351

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