Skip to content

Instantly share code, notes, and snippets.

@dessibelle
Last active December 23, 2015 17:29
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 dessibelle/6668879 to your computer and use it in GitHub Desktop.
Save dessibelle/6668879 to your computer and use it in GitHub Desktop.
Transfers your public SSH key (id_rsa.pub) to the authorized_keys file of a remote computer, allowing for password-less login.
#!/usr/bin/env bash
PROGRAM_NAME=`basename $0`
ARGS=`getopt u:H:h "$@"`
KEY_PATH=~/.ssh/id_rsa.pub
if [ $? != 0 ] ; then
echo "Error parsing arguments. Try $PROGRAM_NAME -h" > /dev/stderr
exit 2
fi
eval set -- "$ARGS"
while true; do
case $1 in
-u)
SSH_USER="$2"; shift 2; continue
;;
-H)
SSH_HOST="$2"; shift 2; continue
;;
-h)
BA="\033[1m"
BD="\033[0m"
UA=`tput smul`
UD=`tput rmul`
echo "$PROGRAM_NAME"
echo ""
echo -e "${BA}USAGE${BD}"
echo -e " $PROGRAM_NAME [${BA}-h${BD}] [${BA}-u${BD} ${UA}username${UD}] [${BA}-H${BD} ${UA}host${UD}] [${UA}[user@]host${UD}] [${UA}path to key${UD}]"
echo ""
echo -e "${BA}GENERAL${BD}"
echo " Transfers your public SSH key (id_rsa.pub) to the authorized_keys file of a remote computer, allowing for password-less login."
echo ""
echo -e "${BA}OPTIONS${BD}"
echo -e " ${BA}-u${BD} ${UA}username${UD}"
echo " Username on host"
echo ""
echo -e " ${BA}-H${BD} ${UA}host${UD}"
echo " Remote hostname"
echo ""
echo -e " ${BA}-h${BD} Display help"
echo ""
exit 0
;;
--)
# no more arguments to parse
shift
break
;;
*)
printf "Unknown option %s\n" "$1"
exit 1
;;
esac
done
# (Try to) determine where to connect (and which key to transfer)
if [ $# -gt 0 ] ; then
#SITE=`echo $(pwd)/"$1"`
if [ -z "$SSH_HOST" ] ; then
SSH_STRING=$1
fi
if [ $# -gt 1 ] ; then
KEY_PATH=$2
else
if [ -n "$SSH_HOST" ] ; then
KEY_PATH=$1
SSH_STRING=""
fi
fi
fi
# Still don't know where to connect, ask for it!
if [ -z "$SSH_STRING" ] && [ -z "$SSH_HOST"] ; then
while :
do
read -p "Host: " SSH_HOST
if [ -n "$SSH_HOST" ] ; then
break
fi
done
fi
# No [user@]host given, let's start with the -H arg
if [ -z "$SSH_STRING" ] ; then
SSH_STRING="$SSH_HOST"
fi
# Now, if there is still no user part in the SSH_STRING, lets add the -u arg
if [ -n "$SSH_STRING" ] && [ -n "$SSH_USER" ] && [[ "$SSH_STRING" != *@* ]] ; then
SSH_STRING="$SSH_USER@$SSH_STRING"
fi
# Alright, this should not be possible. But better safe than sorry, as they say
if [ -z $SSH_STRING ] ; then
echo "No host given. Try $PROGRAM_NAME -h" > /dev/stderr
exit 2
fi
# Dinally! Let's transfer that key
echo `cat $KEY_PATH` | ssh "$SSH_STRING" "mkdir -p ~/.ssh; cat >> ~/.ssh/authorized_keys;"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment