Automate SSH Authorization

I usually work on Linux machines. every time its a time taking task to generate ssh key generation between servers and copy the authorization key.

i have a small script which will generate and copy the files to your desired destinations and makes your task easy

Login to server A

#ssh-keygen -t rsa -b 2048

follow the instructions and complete the key generation with empty passphrase.

#cd /tmp

#vi sshkeycopy.sh

#-------- end of the script -----------

#! /bin/bash

 PATH="/bin:/usr/bin" if [ ! -e ~/.ssh/id_rsa.pub ]; then

 echo "RSA public key file ~/.ssh/id_rsa.pub not found!"

 exit 1

 fi

for desthost in $@; do

 ssh -q "${USER}@${desthost}" \

 "if [ ! -d ~/.ssh ]; then mkdir -m 0700 ~/.ssh; fi; \

 echo $(cat ~/.ssh/id_rsa.pub) >> ~/.ssh/authorized_keys; \

 chmod 0600 ~/.ssh/authorized_keys" || echo "Unable to connect to $desthost"

 done
#-------- start of the script -----------

Save the test using :wq and quit.

# chmod 700 sshkeycopy.sh

Now you are ready to copy the generated keys to the destination servers

# cd /tmp

#./sshkeycopy.sh serverB.linuxgurus.com serverC.linuxgurus.com

For the first time, it will ask password for the destination servers to copy the authorized_keys.

Now you can scp or ssh into destination servers from the current server without any passwords.

- Shankar

About the Author Masroof Ahmad

Leave a Comment:

3 comments
Add Your Reply