Skip to content

Instantly share code, notes, and snippets.

@allex
Last active March 5, 2019 09:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save allex/b6276c69b219714bb50c9fb43e5e9741 to your computer and use it in GitHub Desktop.
Save allex/b6276c69b219714bb50c9fb43e5e9741 to your computer and use it in GitHub Desktop.
#!/bin/sh
# tool script for install ssh authorized key
# GistID: b6276c69b219714bb50c9fb43e5e9741
# Usage:
# > sh -c "$(curl -sL https://git.io/fhAOF)" -- [ -i ~/.ssh/keyfile_or_url -h use@host ]
key_id="http://jk.im.l/ssh.key"
h=
help() {
echo >&2 "add-ssh-key.sh -i <identity_file or url> -h <user@host>"
}
while true; do
opt="$1"
if [ -n "$opt" ]; then
[[ $opt =~ -.* ]] || { help; exit 1; }
fi
shift
case "$opt" in
-i|--identify)
key_id="$1"
[ -n "$key_id" ] || { help; exit 1; }
shift
;;
-h|--host)
h="$1"
shift
;;
'-?'|--help) help ;;
*) break ;;
esac
done
if [ -z "$h" ]; then
read -p "Server (eg: user@host): " h
[ -n "$h" ] || { echo >&2 "Host and Username are required! [ --host u@host ]"; exit 1; }
fi
# parse custom key with --key <KEY_FILE_OR_URL>
if [ -f "$key_id" ]; then
t="$key_id"
elif [[ "$key_id" =~ (https?|ftp|file)://.* ]]; then
t=$(umask 077; mktemp)
trap 'rm -f -- "$t"' 0 1 2 3 9 13 15
curl -sfL "$key_id" > ${t} \
|| { echo >&2 "Fetch authorize key failed!"; exit 1; }
fi
# ref ssh-copy-id
ssh_copy_id() {
ID_FILE="${HOME}/.ssh/id_rsa.pub"
if [ "-i" = "$1" ]; then
shift
# check if we have 2 parameters left, if so the first is the new ID file
if [ -n "$2" ]; then
if expr "$1" : ".*\.pub" > /dev/null ; then
ID_FILE="$1"
else
ID_FILE="$1.pub"
fi
if ! [ -f "$ID_FILE" ]; then
ID_FILE="$1"
fi
shift # and this should leave $1 as the target name
fi
else
if [ x$SSH_AUTH_SOCK != x ] && ssh-add -L >/dev/null 2>&1; then
GET_ID="$GET_ID ssh-add -L"
fi
fi
if [ -z "`eval $GET_ID`" ] && [ -r "${ID_FILE}" ] ; then
GET_ID="cat ${ID_FILE}"
fi
if [ -z "`eval $GET_ID`" ]; then
echo "$0: ERROR: No identities found" >&2
exit 1
fi
if [ "$#" -lt 1 ] || [ "$1" = "-h" ] || [ "$1" = "--help" ]; then
echo "Usage: $0 [-i [identity_file]] [user@]machine" >&2
exit 1
fi
{ eval "$GET_ID" ; } | ssh $1 "exec sh -c 'cd; umask 077; test -d .ssh || mkdir .ssh ; cat >> .ssh/authorized_keys && (test -x /sbin/restorecon && /sbin/restorecon .ssh .ssh/authorized_keys >/dev/null 2>&1 || true)'" || exit 1
cat <<EOF
install authorized key success! ($1)
EOF
ssh "$1" "true" && echo "test authorized keys done!"
}
ssh_copy_id -i "$t" "$h"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment