Skip to content

Instantly share code, notes, and snippets.

@shawn111
Forked from cdelorme/instructions
Last active May 10, 2018 14:43
Show Gist options
  • Save shawn111/23547de8d8184d5bb7332c558c3ed56f to your computer and use it in GitHub Desktop.
Save shawn111/23547de8d8184d5bb7332c558c3ed56f 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
#
# update
#
function update_authorized_keys {
keys=$(wget -qO- https://github.com/$github_user.keys)
echo "$keys" | while read -r key
do
if [ -f "$user_home/.ssh/authorized_keys" ] && ! grep "$key" "$user_home/.ssh/authorized_keys" &> /dev/null
then
echo "$key" >> "$user_home/.ssh/authorized_keys"
echo $user add $key
fi
done
}
while read line; do
user=$(echo $line | cut -d':' -f1)
user_home=$(eval echo ~$user)
github_user=$(echo $line | cut -d':' -f2)
update_authorized_keys
done < $HOME/.config/update-keys.conf
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment