Executing commands remotely on multiple systems via SSH

root's picture

Let's assume you have your systems farm. From one of them you are able to connect to all others with ssh keys already configured.
Now, you create a list with all these systems in it. If you want to temporary skip one system, just put # in front of it, like in our example (server2 disabled).
The ssh options are there to assure you that even if you have ssh configuration problems or one server is down, you won't get stuck on that and everything will go smooth to the end.
In the example below, you will execute uptime via ssh to all servers in the list except server2 (which is commented):

root@gate# cat list
server1
#server2
server3
server4
server5
root@gate# CMD="uptime"
root@gate# SSH="/usr/bin/ssh -o PasswordAuthentication=no -o NumberOfPasswordPrompts=0 -o PreferredAuthentications=publickey -o StrictHostKeyChecking=no"
root@gate# for i in $(cat list|grep -v ^#); do echo "Server $i output:";printf "Connecting to $i...\r"; $SSH $i "$CMD"; done
Server server1 output:
  09:14AM   up 401 days,  11:34,  0 users,  load average: 2.21, 2.10, 2.15
Server server3 output:
  09:14AM   up 562 days,  21:27,  0 users,  load average: 0.14, 0.15, 0.26
Server server4 output:
  09:14AM   up 13 days,  20:16,  0 users,  load average: 1.20, 1.03, 0.87
Server server5 output:
  09:14AM   up 542 days, 27 mins,  0 users,  load average: 0.90, 0.89, 0.86

Now, each time you want to execute another command, you set up the CMD variable.

In the same manner, with different tweaks, you can get a list with the servers on which you cannot connect:

root@gate#  for i in $(cat list|grep -v ^#); do $SSH $i $CMD 2>/dev/null 1>/dev/null || echo $i; done
server4
server5

Obviously, this is just a concept idea and all these commands can be put into a nice script but I leave that to you.
Good Luck!

Thou shalt not steal!

If you want to use this information on your own website, please remember: by doing copy/paste entirely it is always stealing and you should be ashamed of yourself! Have at least the decency to create your own text and comments and run the commands on your own servers and provide your output, not what I did!

Or at least link back to this website.

Recent content

root
root
root
root
root
root
root
root
root
root
root
root
root
root
root
root
root
root
root
root
root
root
root
root
root
root
root
root
root
root