Last active
January 23, 2020 09:55
-
-
Save f0rki/fb8ed9eba9e1dc6c2c5fac19dc839458 to your computer and use it in GitHub Desktop.
Import SSH keys from github with a simple bash script
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
set -eu | |
if ! which jq >/dev/null && which curl >dev/null; then | |
echo "Installing dependencies!" | |
/usr/bin/pacman -Syu --noconfirm curl jq | |
fi | |
if (( $# != 2 )); then | |
echo "Import ssh public keys from github user to authorized_keys" | |
echo "of local user on this system." | |
echo "" | |
echo "usage: $0 <system_user> <github_user>" | |
exit -1 | |
fi | |
SYS_USER="$1" | |
GITHUB_USER="$2" | |
if ! id -u "$SYS_USER"; then | |
echo "No such user on system: '$SYS_USER'" | |
exit 2 | |
fi | |
USER_HOME=$(getent passwd "$SYS_USER" | cut -d ":" -f6) | |
SSH_PATH="$USER_HOME/.ssh/" | |
AUTHORIZED_KEYS="$SSH_PATH/authorized_keys" | |
mkdir -p $SSH_PATH | |
chmod 700 $SSH_PATH | |
chown $SYS_USER $SSH_PATH | |
if /usr/bin/curl -L "http://api.github.com/users/$GITHUB_USER/keys" \ | |
| /usr/bin/jq -r '.[].key' \ | |
> "/tmp/github_keys_$GITHUB_USER" | |
then | |
echo "SUCCESS: added keys from github user $GITHUB_USER" | |
echo "# github ssh-keys for github user $GITHUB_USER" >> "$AUTHORIZED_KEYS" | |
cat "/tmp/github_keys_$GITHUB_USER" >> "$AUTHORIZED_KEYS" | |
chmod 600 "$AUTHORIZED_KEYS" | |
chown "$SYS_USER" "$AUTHORIZED_KEYS" | |
exit 0 | |
else | |
echo "WARNING: failed to fetch ssh public keys from GH" | |
exit 1 | |
fi |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment