July 27, 2011

Setting up password less authentication between two linux machines

Setting up password less authentication between two machines is a common requirement for many distributed software to work, some examples being hadoop, MPI etc ... however it is sometimes also handy if you are a system administrator and frequently login to a remote machine. Now the ssh-copy-id utility already exists to copy the ssh public key from the current machine to the remote machine. But if you have to copy the key from the remote machine to the local machine you have to first login to the remote machine, and then use ssh-copy-id (or some other method) from there. Here is a handy bash script to do the same.


#!/bin/bash
set -x
if [ $# -eq 0 ]; then
echo "Usage : setup_ssh <local_interface> <remote_ip> [<remote_user>]"
echo "Example : setup_ssh wlan0 192.168.0.10"
exit 1
fi
interface=$1
remote_ip=$2
my_ip=$(ifconfig $interface | grep "inet addr" | sed 's/inet addr://g' | awk '{print $1}')
if [ $? -ne 0 ]; then
echo "Could not get the current machines ip"
exit 1
fi
if [ $# -eq 3 ];then 
user=$3
else
user=$USER
fi
if [ "$user" = "root" ]; then
remote_home="/root/.ssh"
else
remote_home="/home/$user/.ssh"
fi
echo "Checking for remote copy program .."
which scp
if [ $? -eq 0 ]; then
remote_copy="scp"
else
which rsync
if [ $? -eq 0 ]; then
remote_copy="rsync"
else
echo "Could not find a remote copy program, quitting !"
exit 1
fi
fi
which ssh-copy-id
if [ $? -ne 0 ]; then
echo "Could not find ssh-copy-id "
exit 1
fi
if ! [ -f ~/.ssh/id_rsa.pub ]; then
echo "Could not find the default public key : ~/.ssh/id_rsa.pub"
exit 1
fi
echo "ssh-copy-id $user@$remote_ip"
ssh-copy-id $user@$remote_ip
$remote_copy $user@$remote_ip:$remote_home/*.pub ./
cat *.pub >> ~/.ssh/authorized_keys
rm -rf *.pub
if [ $? -ne 0 ];then
echo "Copying the public keys failed ... quitting "
exit 1
else
echo "Successfull"
exit 0
fi

Note that the script only works in one of the following two formats :

$ ssh-setup interface remote_ip remote_user 
                                 or
$ ssh-setup interface remote_ip 


The remote ip need not only be an ip address, as you would have already understood from the script, it can also be a hostname or some handle which can be resolved to an ip address.

A sample execution would look like  :


$ ssh-setup wlan0 192.168.0.21 root


Note : This script has only been tested on a linux machine (Fedora 14 ) and I do not assure you of its functionality, use at your own risk.