ssh break out while loop?

From time to time, you might run into tasks like execute commands remotely on different Linux servers regularly, for example collecting logs. A bash script will be handy to do so and likely you will use SSH within the script.

Then don’t be surprised to see your loop doesn’t work any more with SSH in the loop if your script looks like the following:

while read server; do
        ssh $server uptime
done < serverList

It executes once and exits. What’s happening there? That’s because ssh reads from stdin and eats the rest of lines. One trick is to use redirect like “</dev/null” to connect its standard input to nowhere.

ssh $server uptime </dev/null

But a better solution is to use “-n” option:

-n      Redirects stdin from /dev/null (actually, prevents reading from stdin). This must be used when ssh is run in the background. 
ssh -n $server uptime </dev/null

There are some other things to note when put ssh into a script:

  1. use sshpass so that you don’t have to enter the password. Security will be a concern though.
  2. option “-q” to avoid the banner.
  3. option “-oStrictHostKeyChecking=no” to make sure no confirmation is asked for the first connection.
Advertisement

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 )

Facebook photo

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

Connecting to %s