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

Share This Post with Your Friends over Social Media!

About the Author Atul Kumar

Leave a Comment:

3 comments
tttttt says June 22, 2009

are you aware of the ssh-copy-id utility which is provided with RHEL5?

Reply
Shanker says June 22, 2009

I am aware of this Utility. This article is generalized for other versions which doesn’t have this utility.

Reply
Laurent Schneider says June 22, 2009

if you are lazy you could do

cat ~/.ssh/id_*pub|ssh desthost tee -a .ssh/authorized_keys

Reply
Add Your Reply

[index]
[index]
[523.251,1046.50]
[523.251,1046.50]