|
#!/usr/bin/env bash |
|
|
|
USER='' |
|
HOME_DIR='' |
|
DEBUG=false |
|
KEY_FILE='' |
|
|
|
function setuser { |
|
if [ -z "$1" ]; then |
|
echo "RUNTIME EXCEPTION: No user supplied" |
|
exit 1 |
|
fi |
|
debug "Setting user $1" |
|
USER="$1" |
|
HOME_DIR="$(eval echo ~$USER)" |
|
debug "Set home dir to: ${HOME_DIR}" |
|
return 0 |
|
} |
|
|
|
function debug { |
|
${DEBUG} && echo "$@" |
|
return 0 |
|
} |
|
|
|
function addkeys { |
|
# ensure the user has an ~/.ssh/ dir |
|
debug "Adding .ssh dir for user" |
|
mkdir -p -m 700 "${HOME_DIR}/.ssh/" |
|
# If the authorized keys file exists, remove our managed keys |
|
if [ -f "${HOME_DIR}/.ssh/authorized_keys" ]; then |
|
debug "authorized keys file exists, removing automatically managed keys" |
|
sed -i '/### AUTOMATICALLY MANAGED KEYS ###/,/### END OF AUTOMATICALLY MANAGED KEYS ###/d' "${HOME_DIR}/.ssh/authorized_keys" |
|
else |
|
debug "Authorized keys file doesn't exist, adding it" |
|
touch "${HOME_DIR}/.ssh/authorized_keys" |
|
fi |
|
debug "Adding automatically managed keys" |
|
# Add our keys to the authorized keys file |
|
echo '### AUTOMATICALLY MANAGED KEYS ###' >> "${HOME_DIR}/.ssh/authorized_keys" |
|
|
|
#loop over lines in file |
|
# This is looping over each word and not each line |
|
while read -r line; do |
|
if [[ "${line}" == \#* ]]; then |
|
continue |
|
fi |
|
debug "Adding key: ${line}" |
|
echo "${line}" >> "${HOME_DIR}/.ssh/authorized_keys" |
|
done <<< "${KEYS}" |
|
|
|
echo '### END OF AUTOMATICALLY MANAGED KEYS ###' >> "${HOME_DIR}/.ssh/authorized_keys" |
|
debug "finished adding keys" |
|
debug "Ensuring ownership of .ssh is correct" |
|
# ensure ownership and permissions are correct |
|
chown -R "${USER}:" "${HOME_DIR}/.ssh" |
|
debug "Making sure authorized keys file permissions are set correctly" |
|
chmod 0600 "${HOME_DIR}/.ssh/authorized_keys" |
|
|
|
return 0 |
|
|
|
} |
|
|
|
while getopts "u:k:d" OPTION; do |
|
case ${OPTION} in |
|
u ) setuser "${OPTARG}" |
|
;; |
|
k ) KEY_FILE="${OPTARG}" |
|
;; |
|
d ) DEBUG=true |
|
;; |
|
esac |
|
done |
|
|
|
if [ -z ${USER} ]; then |
|
setuser `whoami` |
|
fi |
|
|
|
if [ -z ${KEY_FILE} ]; then |
|
echo "MISSING ARGUMENT: Key file (-k) required" |
|
exit 1 |
|
fi |
|
|
|
KEYS=$(wget -q -O - ${KEY_FILE}) |
|
|
|
addkeys |