Automating connecting with ssh to a series of hosts

I sometimes need to a large number of servers one after the other to run a command. For example if we want to see how full the home partition is on all our servers. The command we want to run is the disk free command in human readable format, df -h /home. The first step is to have a text file with a list of servers that you want to connect to.

cat servers.txt

Then create a loop to cycle through the list and connect to each in turn and runĀ  the command you want.

for i in `cat servers.txt`;do 
  echo $i;ssh $i "df -h /home"

Sometimes when one of your servers is down or disconnected there is a long timeout in establishing the connection ass ssh waits for the tcp connection to fail. You can get around that by using the ConnectTimeout ssh option. This usually run this type of command all on one line.

for i in `cat servers.txt`;do echo $i;ssh -o ConnectTimeout=3 $i "df -h /home";done

Keep in mind that this will connect to the servers in sequence so another approach might be Parallel ssh mentioned on David O’Yeats’s podcast, although that is probably not going to be installed by default.

This entry was posted in Podcasts. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *