Configure Passwordless SSH on Multiple Servers and Execute Commands on Multiple servers in Linux

1. On Server 1 (192.168.1.67)

ssh-keygen -t rsa

cd .ssh/

scp -r id_rsa.pub root@192.168.1.68:/root/.ssh/authorized_keys

2. On Server 2 (192.168.1.68)

ssh-keygen -t rsa

cd .ssh

cat id_rsa.pub >> authorized_keys

3. Send Server 2 authorized key to Server 1 (192.168.1.67)

scp -r authorized_keys root@192.168.1.67:/root/.ssh
4. Test from server 1

ssh root@192.168.1.68

Test from Server 2

ssh root@192.168.1.67
5. On Server 3 (192.168.1.69)

ssh-keygen -t rsa

cd .ssh

cat id_rsa.pub >> authorized_keys
6. On Server 4 (192.168.1.70)

ssh-keygen -t rsa

cd .ssh

cat id_rsa.pub >> authorized_keys

7. 5. On Server 5 (192.168.1.71)

ssh-keygen -t rsa

cd .ssh

cat id_rsa.pub >> authorized_keys

8. 5. On Server 6 (192.168.1.72)

ssh-keygen -t rsa

cd .ssh

cat id_rsa.pub >> authorized_keys

9. Now on Server 1  192.168.1..67

create a file called hosts.txt in /root directory, and save the ips of the below host

192.168.1.68
1192.168.1.69
192.168.1.70
192.168.1.71
192.168.1.72

To excute a remote command on all the hosts from server 1 run below command :

— Run Single Command —

for host in $(cat hosts.txt); do ssh “$host” “date” > “output.$host”; done
— Run Multiple Commands —

for host in $(cat hosts.txt); do ssh “$host” “uname -a && date && df -h” > “output.$host”; done

#Double-ampersands will execute the next command only if the preceding command exits with a status of zero. In the below example,

for host in $(cat hosts.txt); do ssh “$host” “uname -a ; date ; df -h” > “output.$host”; done

#Semi-colons will execute all commands regardless of exit status. In the below example, all three commands will be run.

# In short: double-ampersands should be used if the commands depend on each other, semi-colons should be used if they don’t.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s