Skip to content

Instantly share code, notes, and snippets.

@bigbosst
Last active August 29, 2015 14:09
Show Gist options
  • Save bigbosst/767998d4046c54c8cf81 to your computer and use it in GitHub Desktop.
Save bigbosst/767998d4046c54c8cf81 to your computer and use it in GitHub Desktop.
SSH RE-KEY
#!/bin/bash
# Shell script to install your public key on a remote machine
# Takes the remote machine name as an argument.
# The remote machine must accept password authentication,
# one of the other keys in your ssh-agent,
# or accept the key passed with the Identity (-i) flag for this to work.
# -f : public identity to copy to the known_hosts file
# -i : private key to use to connect to the server
SSH_OPS=""
ID_FILE="${HOME}/.ssh/id_rsa.pub"
usage() { echo -e "Usage: ssh-rekey-id [-f <STRING>] [-i <STRING>] [USERID@]HOSTNAME\n -f <STRING> for pub key file\n -i <STRING> for ssh identy file";}
while getopts "f:i:h:" opt; do
case "${opt}" in
f)
ID_FILE=${OPTARG}
;;
i)
SSH_OPS="${SSH_OPS} -i${OPTARG}"
;;
h|\?)
usage
exit 1
;;
esac
done
shift $((OPTIND-1))
if [ -z "$1" ]; then
usage
exit 1
else
# strip any trailing colon
HOST=`echo $1 | sed 's/:$//'`
fi
if [ -r "${ID_FILE}" ] ; then
GET_ID="cat ${ID_FILE}"
fi
if [ -z "`eval ${GET_ID}`" ]; then
echo ${ID_FILE}
echo "$0: ERROR: No identities found" >&2
exit 1
fi
#echo ' ssh ${SSH_OPS} ${HOST} "umask 077; test -d ~/.ssh || mkdir ~/.ssh ; cat >> ~/.ssh/authorized_keys" '
{ eval "${GET_ID}" ; } | ssh ${SSH_OPS} ${HOST} "umask 077; test -d ~/.ssh || mkdir ~/.ssh ; cat >> ~/.ssh/authorized_keys" || exit 1
cat <<EOF
Now try logging into the machine, with "ssh '${HOST}'", and check in:
~/.ssh/authorized_keys
to make sure we haven't added extra keys that you weren't expecting.
EOF
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment