Thursday, 25 April 2013

Unix Shell Script: ssh under while loop

When you try to do ssh in while loop  as follows:, it will do ssh once then quit the loop. In other words looping won't happen

while read line
do
 ssh  user@$line "jps"
done

So the solution is run ssh as background process i.e use -n option with ssh as follows:

while read line
do
 ssh -n user@$line "jps"
done

One more benefit, executing it in backgroud is that in case there is some error while doing ssh to some machine, loop wont quit since process is running in background. So it will fire ssh process on all other machines that appear after the erroneous machine in the file

Also, you can use for loop for it.

OIFS=$IFS #Original Internal field separator
IFS=" # Setting Internal Field Separator to new line
"
for  line in `cat filename`
do
ssh user@$line "jps"
done

No comments:

Post a Comment