Skip to content

Instantly share code, notes, and snippets.

@ryantology
Forked from codeslinger/gist:3494
Last active December 6, 2018 19:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save ryantology/1c813572c270c2e591df to your computer and use it in GitHub Desktop.
Save ryantology/1c813572c270c2e591df to your computer and use it in GitHub Desktop.
Retrieve SSH public keys from GitHub and install to authorized_keys.
#!/bin/bash
# vim:set ts=4 sw=4 et ai:
# Retrieve SSH public keys from GitHub and install to authorized_keys.
GITHUB_USERS=(USER1 USER2)
INSTALL_FILE=/home/USER/.ssh/authorized_keys
TMP_KEY=/tmp/ssh.key
CURL=/usr/bin/curl
CURLOPTS="--retry 3 --retry-delay 2 --silent --fail -o $TMP_KEY"
if [ ! -d `dirname $INSTALL_FILE` ]; then
mkdir -p -m 700 `dirname $INSTALL_FILE`
fi
# Backup existing key
if [ -f $INSTALL_FILE ]; then
mv $INSTALL_FILE $INSTALL_FILE.bak
fi
for GITHUB_USER in ${GITHUB_USERS[@]}; do
SUCCESS=0
ATTEMPT=0
MAX_ATTEMPTS=10
while [ $SUCCESS -eq 0 -a $ATTEMPT -lt $MAX_ATTEMPTS ] ; do
# attempt to retrieve the SSH public key and install it
KEY_URL="https://github.com/$GITHUB_USER.keys"
$CURL $CURLOPTS $KEY_URL
if [ $? -eq 0 -a -f $TMP_KEY ]; then
cat $TMP_KEY >> $INSTALL_FILE
echo "" >> $INSTALL_FILE
echo "SSH key added to $INSTALL_FILE from $KEY_URL"
rm -f $TMP_KEY
SUCCESS=1
fi
# print out status and wait for a bit if we failed
ATTEMPT=$(($ATTEMPT + 1))
if [ $SUCCESS -eq 0 ]; then
echo "SSH key retrieval attempt $ATTEMPT failed"
sleep 5
fi
done
done
# either we got it or we just gave up
if [ -f $INSTALL_FILE ]; then
chmod 600 $INSTALL_FILE
echo "SSH Keys Installed"
else
echo "-=[ FATAL ]=- SSH key could not be retrieved!!!"
if [ -f $INSTALL_FILE.bak ]; then
mv $INSTALL_FILE.bak $INSTALL_FILE
fi
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment