DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

Automatically Authorize A Remote Host (SSH Key Swap)

04.08.2005
| 13752 views |
  • submit to reddit
        use with caution!  This script will copy your pub key to a remote host so you can login or run remote scripts without a password.  IMPORTANT: if you need to run a single script on the remote host, it would be better to authorize a key for just that script.

#!/bin/bash
# kumar.mcmillan -at- farmdev.com

function usage()
{
    echo ""
    echo "Authorizes a host for automatic SSH use by sending your key to the remote host ..."
    echo "Usage: $0 remote_host_to_authorize [username:=defaults to current username]"
    echo ""
}

function cleanup()
{
    if [ -f $TEMP_PUB_KEY_XFER ]
    then
        rm $TEMP_PUB_KEY_XFER
    fi
}

function exit_on_error()
{
    cleanup
    exit 1
}

if [ $# -lt 1 -o "$1" = "-h" -o "$1" = "--help" ]
then
    usage
    exit 0
fi

PUB_KEY=~/.ssh/id_dsa.pub
if [ $# -eq 2 ]; then
    USER=$2
else
    USER=`whoami`
fi
HOST_TO_AUTH=$1
TEMP_PUB_KEY_XFER=/tmp/$USER"_TEMP_KEY"

echo "checking for $PUB_KEY ..."
if [ ! -f $PUB_KEY ]; then
    echo "generating your dsa public key (leave passphrase blank and save to $PUB_KEY when prompted) ..."
    ssh-keygen -t dsa
    if [ $? -ne 0 ]; then
        echo "ssh-keygen failed"
        exit_on_error
    fi
fi
echo "OK"

echo "for the following commands you will be asked to supply your password for $HOST_TO_AUTH :"

echo "copying a temp pub key to $HOST_TO_AUTH ..."
cat $PUB_KEY > $TEMP_PUB_KEY_XFER
chmod 700 $TEMP_PUB_KEY_XFER
echo "OK"

remote_key=`basename $TEMP_PUB_KEY_XFER`
scp $TEMP_PUB_KEY_XFER $USER@$HOST_TO_AUTH:~/$remote_key
if [ $? -ne 0 ]; then
    echo "scp failed"
    exit_on_error
fi
    
echo "authorizing $HOST_TO_AUTH for automatic SSH use ..."
ssh $USER@$HOST_TO_AUTH "cat ~/$remote_key >> ~/.ssh/authorized_keys; rm ~/$remote_key"
if [ $? -ne 0 ]; then
    echo "ssh failed"
    exit_on_error
fi
echo "OK"

cleanup
echo "authorization successful!  you can now login automatically to $HOST_TO_AUTH"
exit 0