Skip to content

Instantly share code, notes, and snippets.

@onelastjedi
Last active January 17, 2016 14:13
Show Gist options
  • Save onelastjedi/5c4e91d72adc306fa635 to your computer and use it in GitHub Desktop.
Save onelastjedi/5c4e91d72adc306fa635 to your computer and use it in GitHub Desktop.
Better/quicker way to add ssh key to servers
#!/bin/sh
# Define the usage
usage="Usage: ssh-keyadd [-h this help] [-l username] [-p port] [-k key file] [-a remote authorized_keys] remote_server..."
# Check for Options and Arguments
while getopts ":l:p:k:a:h:" opt; do
case $opt in
l ) user=$OPTARG;;
p ) if [ $(echo $OPTARG | grep '^[0-9]*$') ];then
port=$OPTARG
else
echo "Port needs to be set to a number"
echo $usage
exit
fi;;
k ) key=$OPTARG;;
a ) auth=$OPTARG;;
h ) echo -e $usage;;
\? ) echo -e $usage
exit;
esac
done
shift $((OPTIND -1))
if [ -z "$@" ]; then
echo $usage
exit 1
fi
# Define the variables
user=${user:-`whoami`} # If a user name isn't passed I'll assume I can use your current username
port=${port:-22} # Unless I was told differently, I will use default SSH port
key=${key:-"$HOME/.ssh/id_rsa.pub"} # Location of local public key you want to push
auth=${auth:-"~/.ssh/authorized_keys"} # Authorized file on remote server
remote=${1:?"You need to provide a remote server."}
if [ $(echo $remote | grep '^[0-9a-zA-Z.-_]*$') ];then
set=1
else
echo "Remote server needs to be an IP address of URI"
echo $usage
exit
fi
# Update remote server with key. This should be the last time
# you are prompted for a password
echo "Adding the following key -> $key "
echo "To the following remote server -> $remote "
echo "For the following user -> $user "
echo "If this is all correct, please enter password for the remote server"
cat $key | ssh -l $user -p $port $remote sh -c "cat >> $auth "
echo "------------KEY ADDED--------------"
# If Key updates successfully we should be able to
# SSH to the location. Let's try
echo "The key has been added to the remote server, now lets try and connect"
ssh -l $user -p $port $remote
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment