curl -s https://urlto/install.sh | INSTALL_PUBLIC_KEY="ssh-rsa AAAAB3Nzwhatever mrl22@sfsdfsdfsdfsdf" bash -
Created
September 2, 2022 19:53
-
-
Save mrl22/8fee53d438d41940a1529ab527e2a979 to your computer and use it in GitHub Desktop.
First install
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 | |
# | |
# NAME | |
# install.sh - Install manager user to connect to a server | |
# | |
# DESCRIPTION | |
# Add a public key to the authorized_hosts file of the user running this | |
# command. Before doing that, this script checks that the user is | |
# either `root` or can run `sudo`. | |
# | |
# The public key is given in the environment variable INSTALL_PUBLIC_KEY. | |
# | |
# -h, --help | |
# Show documentation and exit | |
# | |
############################################################################## | |
set -o errexit -o nounset | |
usage() { | |
local exit_code="$1" | |
while IFS= read -r line | |
do | |
case "${line}" in | |
'#!'*) | |
;; | |
'##'*) | |
exit ${exit_code} | |
;; | |
*) | |
printf '%s\n' "${line#?}" | |
;; | |
esac | |
done < "$0" | |
} | |
check_user() { | |
local user=$(whoami) | |
local uid=$(id -u) | |
if [[ ${user} != root && ${uid} != 0 ]] | |
then | |
sudo -v || exit 1 | |
fi | |
printf '%s' "${user}" | |
} | |
create_authorized_keys_file() { | |
local user="$1" | |
local dir="/home/${user}/.ssh" | |
if [[ ${user} = root ]] | |
then | |
dir="/root/.ssh" | |
fi | |
if [[ ! -d ${dir} ]] | |
then | |
mkdir ${dir} | |
fi | |
chmod 700 ${dir} | |
local key_file="${dir}/authorized_keys" | |
touch ${key_file} | |
chmod 600 ${key_file} | |
printf '%s' "${key_file}" | |
} | |
authorize_key() { | |
local key_file="$1" | |
local public_key="$2" | |
# make sure there's a line break before adding another key | |
echo >> ${key_file} | |
echo "${public_key}" >> ${key_file} | |
} | |
success() { | |
local user="$1" | |
printf 'Done! You must connect as user: %s\n' "${user}" | |
echo | |
} | |
case "${1:-}" in | |
'--help') | |
usage 0 | |
;; | |
*) | |
;; | |
esac | |
[[ -v INSTALL_PUBLIC_KEY ]] || usage 1 | |
public_key="${INSTALL_PUBLIC_KEY}" | |
user="$(check_user)" | |
key_file="$(create_authorized_keys_file ${user})" | |
authorize_key "${key_file}" "${public_key}" | |
success "${user}" | |
exit 0 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment