carlessanagustin
12/7/2016 - 5:47 PM

SHELL: Manage SSH key creation and distribution: for GitHub, auto login to remote instances, ....

SHELL: Manage SSH key creation and distribution: for GitHub, auto login to remote instances, ....

#!/bin/bash

DEBUG=false
OPTIND=1
PASSPHRASE=""

show_help() {
cat << EOF
Usage: ${0##*/} [-hp] [-f OUTPUTFILE] [-r REMOTE_HOST] [-c COMMENT]
Generate SSH key and copy it to remote if needed.

    -h               display this help
    -r REMOTE_HOST   send file to remote host
    -f OUTPUTFILE    output filename
    -c COMMENT       ssh key comment
    -p               optional ssh passphrase

EOF
}

while getopts hpr:f:c: opt; do
    case $opt in
        h)  show_help
            exit 0
            ;;
        r)  REMOTE_HOST=$OPTARG
            ;;
        f)  OUTPUTFILE=$OPTARG
            ;;
        c)  COMMENT=$OPTARG
            ;;
        p)  printf "Enter passphrase [none]: "
            read -r PASSPHRASE
            ;;
        *)  show_help >&2
            exit 1
            ;;
    esac
done

if [ $OPTIND -eq 1 ]; then
  show_help
  exit 0
fi
shift "$((OPTIND-1))"

if [ -f "$OUTPUTFILE" ]
then
    echo "File $OUTPUTFILE does exist"
    exit 0
fi

if [ -z ${COMMENT} ];
then
  echo Running: ssh-keygen -q -t rsa -b 4096 -f ${OUTPUTFILE} -N \"$PASSPHRASE\"
  if ! $DEBUG ; then ssh-keygen -q -t rsa -b 4096 -C "${COMMENT}" -f ${OUTPUTFILE} -N \"$PASSPHRASE\" ; fi
else
  echo Running: ssh-keygen -q -t rsa -b 4096 -C "${COMMENT}" -f ${OUTPUTFILE} -N \"$PASSPHRASE\"
  if ! $DEBUG ; then ssh-keygen -q -t rsa -b 4096 -C "${COMMENT}" -f ${OUTPUTFILE} -N \"$PASSPHRASE\" ; fi
fi

echo Running: ssh-agent
if ! $DEBUG ; then eval "$(ssh-agent -s)" ; fi

echo Running: ssh-add ${OUTPUTFILE}
if ! $DEBUG ; then ssh-add $OUTPUTFILE ; fi

if [ ! -z ${REMOTE_HOST} ];
then
  echo Running: ssh-copy-id -i ${OUTPUTFILE} ${REMOTE_HOST}
  if ! $DEBUG ; then ssh-copy-id -i $OUTPUT_FILE $REMOTE_HOST ; fi
fi

# END