Last active
April 19, 2024 16:11
-
-
Save gtrabanco/eae211bb55a06586111303d9fec1caa1 to your computer and use it in GitHub Desktop.
Shell script to use my github ssh keys to access my server and updates automatically daily =)
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
#!/usr/bin/env bash | |
# GIT_USERNAME="" | |
GIT_PUBLIC_KEYS_AUTHORIZED_KEYS_FILE="${GIT_PUBLIC_KEYS_AUTHORIZED_KEYS_FILE:-${HOME}/.ssh/authorized_keys}" | |
GIT_PUBLIC_KEYS_START="## Start of git public keys" | |
GIT_PUBLIC_KEYS_STOP="## End of git public keys" | |
tmp_file=$(mktemp) | |
clean() { | |
rm -f "$tmp_file" "${GIT_PUBLIC_KEYS_AUTHORIZED_KEYS_FILE}.gitkeys" | |
} | |
trap clean EXIT SIGTERM SIGINT | |
GIT_URL="https://github.com/${GIT_USERNAME}.keys" | |
if [ ! -f "${GIT_PUBLIC_KEYS_AUTHORIZED_KEYS_FILE}" ]; then | |
echo "authorized_keys file could not be found on: '${GIT_PUBLIC_KEYS_AUTHORIZED_KEYS_FILE}' file path" | |
exit 1 | |
fi | |
if ! grep -q "${GIT_PUBLIC_KEYS_START}" "${GIT_PUBLIC_KEYS_AUTHORIZED_KEYS_FILE}"; then | |
echo "${GIT_PUBLIC_KEYS_START}" | tee -a "${GIT_PUBLIC_KEYS_AUTHORIZED_KEYS_FILE}" > /dev/null 2> /dev/null | |
echo "${GIT_PUBLIC_KEYS_STOP}" | tee -a "${GIT_PUBLIC_KEYS_AUTHORIZED_KEYS_FILE}" > /dev/null 2> /dev/null | |
fi | |
start_line="$(grep --line-number "${GIT_PUBLIC_KEYS_START}" "${GIT_PUBLIC_KEYS_AUTHORIZED_KEYS_FILE}" | awk -F ':' '{print $1}' | head -n 1)" | |
end_line="$(grep --line-number "${GIT_PUBLIC_KEYS_STOP}" "${GIT_PUBLIC_KEYS_AUTHORIZED_KEYS_FILE}" | awk -F ':' '{print $1}' | head -n 1)" | |
if ! curl -fs "${GIT_URL}" --output "${GIT_PUBLIC_KEYS_AUTHORIZED_KEYS_FILE}.gitkeys"; then | |
exit 2 | |
fi | |
tee "$tmp_file" < "${GIT_PUBLIC_KEYS_AUTHORIZED_KEYS_FILE}" > /dev/null 2> /dev/null | |
{ | |
head -n "${start_line}" "${tmp_file}" | |
cat "${GIT_PUBLIC_KEYS_AUTHORIZED_KEYS_FILE}.gitkeys" | |
tail -n "+${end_line}" "${tmp_file}" | |
} | tee "${GIT_PUBLIC_KEYS_AUTHORIZED_KEYS_FILE}" > /dev/null 2> /dev/null |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Usage:
GIT_USERNAME="gtrabanco" ./git-public-keys.sh
Better usage with crontab and you will have synced ssh keys to access your remote servers =)
Important! Replace with your git username or you will be granting access to your terminal to me