Wednesday, September 25, 2013

BASH Script to Register RSA Pulic Key with Remote Host

I wanted to be able to script the installation of an RSA public key on a remote host so I could have "password-less" access to the host via SSH.  This is what I came up with.

Note:  I am a developer, not a BASH ninja.  If you have recommendations to improve this script, let me know.

Before I show the script, this is how you use it:

# The User and Host are together.  
# I decided to not make it any more complicated than it needed to be.
sh register_pub_key.sh user@remotehost


You will be prompted for passwords as necessary.

Here's a look at the console output of the script:



And here's the BASH script (named register_pub_key.sh):

#!/bin/bash

# Variables
USER_AND_HOST=$1

line="---------------------------------------------"

echo "REGISTERING RSA PUBLIC KEY WITH HOST: $REMOTE_HOST"

echo $line

echo "This script will prompt during the process since"
echo "you have not yet installed the RSA key with the"
echo "server.  Please be patient; this should be done"
echo "shortly."

echo $line

# Ensure the RSA Public Key exists.
if [ ! -e ~/.ssh/id_rsa.pub  ]
then

    echo "No public SSH key found..."

    echo "Generating SSH key.  Follow the prompts:"

    echo $line

    ssh-keygen -t rsa

    echo $line

    if [ ! $? ]
    then

        echo "Key Generation was not successful.  Exiting."

        exit 1
    fi
fi

echo $line

echo "Ensuring remote .ssh directory exists."
echo "You will need to enter the remote host's password."

ssh $USER_AND_HOST "mkdir -p ~/.ssh/"

echo $line

echo "Copying key to remote host."
echo "You will need to enter the remote host's password."

echo $line

scp ~/.ssh/id_rsa.pub "$USER_AND_HOST:~"

echo $line

echo "Adding the key to the set of 'authorized_keys'..."
echo "You will need to enter the remote host's password."

ssh $USER_AND_HOST "cat id_rsa.pub >> .ssh/authorized_keys"

echo $line

echo "Cleaning up key and testing SSH access..."
echo "IF YOU HAVE TO ENTER A PASSWORD, IT'S FAILED!!!!"

ssh $USER_AND_HOST "rm ~/id_rsa.pub"

RESULT=$?

echo $line

if [ RESULT ]
then
   echo "Your public key was successfully added to the host."
else
   echo "Epic fail mate!  Your key was NOT added to the host."
fi

echo $line

echo "Ensure you can access the server using the following command:"
echo "ssh $USER_AND_HOST \"ls -lah ~/.ssh\""

In the next post, I'm going to demonstrate how to reduce the number of operations considerably by performing this task using Ansible.

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.