1

I am using a script to connect to multiple servers. At the moment, I am using something like:

for SERVER in server1 server2 server3 ; do ssh $SERVER "my-command" ; done

I have to specify the (many) servers every time. I was wondering if there is a better way, for example if ssh has any possibility to define "groups of servers", so that I could refer to it as

for SERVER in $SERVERLIST ; do ssh $SERVER "my-command" ; done

or is this a bad idea, and should be done in bash instead?

Martin Vegter
  • 358
  • 75
  • 236
  • 411

1 Answers1

1

You can set a variable $SERVERLIST yourself, in your shell.

$ SERVERLIST="server1 server2 server3"

You could also put them in a file and for loop through the file.

$ for SERVER in $(<servers.txt) ; do ssh $SERVER "my-command" ; done
slm
  • 369,824
  • The one thing that makes me nervous about your answer, is that it assumes that the server names don't contain any funny characters, which is probably fine in this case, but is something you need to watch out for in other cases. I would recommend passing a null separated list to xargs which is immune to this problem. – hildred Nov 23 '13 at 00:05
  • @hildred - if they're actual DNS hostnames then this isn't as big an issue as it is with file names. For example, new lines which can be used for file names cannot be used for hostnames. Also other weird characters such as &, ?, etc. are not legal either, so I think your point is moot here. – slm Nov 23 '13 at 01:11