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.
Note that the script only works in one of the following two formats :
$ ssh-setup interface remote_ip remote_user
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.
#!/bin/bashset -xif [ $# -eq 0 ]; then echo "Usage : setup_ssh <local_interface> <remote_ip> [<remote_user>]" echo "Example : setup_ssh wlan0 192.168.0.10" exit 1fiinterface=$1remote_ip=$2my_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 1fiif [ $# -eq 3 ];then  user=$3else user=$USERfiif [ "$user" = "root" ]; then remote_home="/root/.ssh"else remote_home="/home/$user/.ssh"fiecho "Checking for remote copy program .."which scpif [ $? -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 fifiwhich ssh-copy-idif [ $? -ne 0 ]; then echo "Could not find ssh-copy-id " exit 1fiif ! [ -f ~/.ssh/id_rsa.pub ]; then echo "Could not find the default public key : ~/.ssh/id_rsa.pub" exit 1fiecho "ssh-copy-id $user@$remote_ip"ssh-copy-id $user@$remote_ip$remote_copy $user@$remote_ip:$remote_home/*.pub ./cat *.pub >> ~/.ssh/authorized_keysrm -rf *.pubif [ $? -ne 0 ];then echo "Copying the public keys failed ... quitting " exit 1else echo "Successfull" exit 0fiNote 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.
No comments:
Post a Comment