Skip to content

Instantly share code, notes, and snippets.

@koshatul
Created February 24, 2016 04:23
Show Gist options
  • Save koshatul/76cef845a4fbe6691cb5 to your computer and use it in GitHub Desktop.
Save koshatul/76cef845a4fbe6691cb5 to your computer and use it in GitHub Desktop.
ssh-copy-id replacement to copy only if key auth fails
#!/bin/bash
########################################################################################
## ssh-copy-id-if-needed
##
## Copies specified identity file to specified server
##
usage() {
echo "usage: $0 [-i [identity_file]] [user@]machine" >&2
exit 1
}
IDENTITY_FILE=""
while getopts “hi:” OPTION
do
case $OPTION in
h)
usage
;;
i)
IDENTITY_FILE="${OPTARG}"
;;
?)
usage
;;
esac
done
REMOTE_HOST="${@:$OPTIND:1}"
if [[ "${IDENTITY_FILE}" == "" ]]; then
usage
fi
# echo "IDENTITY_FILE: ${IDENTITY_FILE}"
# echo "REMOTE_HOST: ${REMOTE_HOST}"
SSH_AUTH_SOCK=/dev/null ssh -o "BatchMode yes" -i "${IDENTITY_FILE}" "${REMOTE_HOST}" uptime > /dev/null 2> /dev/null
RV=${?}
if [[ ${RV} != 255 ]]; then
echo "error: Key may already be on server (RV not 255)" >&2
exit 99
fi
GET_ID="$(cat "${IDENTITY_FILE}")"
{ echo "${GET_ID}" ; } | ssh ${REMOTE_HOST} -i "${IDENTITY_FILE}" "umask 077; test -d .ssh || mkdir .ssh ; cat >> .ssh/authorized_keys" || exit 1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment