Skip to content

Instantly share code, notes, and snippets.

@djsipe
Last active October 31, 2019 16:44
Show Gist options
  • Save djsipe/4e941b7cebbb2871ef346b15440c2976 to your computer and use it in GitHub Desktop.
Save djsipe/4e941b7cebbb2871ef346b15440c2976 to your computer and use it in GitHub Desktop.
Automat SSH Key Configuration on Remote Host
#!/bin/bash
echo This script will attempt to set your public SSH key on the server you designate.
Host=$1
KeyFile=`eval echo "~$USER"`"/.ssh/id_rsa.pub"
KeyFile=${2:-$KeyFile}
# Attempt to ssh without a password
ssh -o BatchMode=yes $Host true 2> /dev/null
# If the above SSH command succeded we don't need to do anything.
if [ $? -eq 0 ];
then
echo ---
echo "🎉 This server is already configured. No action taken."
exit 1
fi
if [ ! -f $KeyFile ];
then
echo ---
echo "😫 KeyFile '${KeyFile}' does not exist."
exit 1
fi
echo "Host to target: ${Host}"
echo "Public key file: ${KeyFile}"
echo ---
echo "Creating .ssh directory."
ssh $Host 'mkdir -p ~/.ssh'
echo ---
echo "Coping public key."
cat $KeyFile | ssh $Host 'cat >> ~/.ssh/authorized_keys'
echo ---
echo Attempting to connect...
ssh $Host
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment