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:
- use sshpass so that you don’t have to enter the password. Security will be a concern though.
- option “-q” to avoid the banner.
- option “-oStrictHostKeyChecking=no” to make sure no confirmation is asked for the first connection.