-1

This question already has an answer here:

I need to login and collect output of below commands from multiple GNU/Linux servers through SSH. I have done password-less SSH authentication. I wanted to do this with bash script.

df -lh | awk '{if ($5 >= 20) { print $6 "  " $2 "   "  $3  "  " $5 }}'
top -b -n1 | grep "Cpu(s)" | awk '{print 100 - $5}'

I tried the command below, but instead of a quoted "command", if giving single command like df it's working .. but giving like long commands:

df -lh | awk '{if ($5 >= 20) { print $6 "  " $2 "   "  $3  "  " $5 }}'
top -b -n1 | grep "Cpu(s)" | awk '{print 100 - $5}'

it's not working..

marked as duplicate by Gilles shell-script Dec 17 '15 at 21:49

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

  • What's the difference between the two snippets? – lese Dec 16 '15 at 15:00
  • What do you mean by “not working”? What commands did you actually run (what you show doesn't involve SSH)? – Gilles Dec 17 '15 at 21:48
1

I would recommend using some parallel SSH tool such as 'clush' or 'pdsh' ,the output will be much more elegant.

Say our server names are 'host01' till 'host09', your command would look like this:

clush -Bw host0[1-9] "df -lh | awk '{if (\$5 >= 20) { print \$6 \""  \"" \$2 "\"   \""  \$3  "\"  \"" \$5 }}';top -b -n1 | grep 'Cpu(s)' | awk '{print 100 - \$5}'"

Pay attention to the escaping.

0

step 1: write it to a script

cat script.sh
df -lh | awk '{if ($5 >= 20) { print $6 "  " $2 "   "  $3  "  " $5 }}'
top -b -n1 | grep "Cpu(s)" | awk '{print 100 - $5}'

step 2: scp it to hosts. (scp is secure copy), host is in $h

scp script.sh $h:/tmp

step 3: execute it

ssh $h bash /tmp/script.sh

You may wish to redirect output

ssh $h bash /tmp/script.sh > result-$h.txt
0

If you want to run those lines without writing a separated script file, you will need to enclose the commands with double quotes and escape any character that might conflict with that. For example:

ssh your-host "
df -lh | awk '{if (\$5 >= 20) { print \$6 \"  \" \$2 \"   \"  \$3  \"  \" \$5 }}'
top -b -n1 | grep \"Cpu(s)\" | awk '{print 100 - \$5}'"

Or using single quotes:

ssh your-host'
df -lh | awk '"'"'{if ($5 >= 20) { print $6 "  " $2 "   "  $3  "  " $5 }}'"'"'
top -b -n1 | grep "Cpu(s)" | awk '"'"'{print 100 - $5}'"'"

Or using here-document:

ssh your-host "$(cat << 'END'
df -lh | awk '{if ($5 >= 20) { print $6 "  " $2 "   "  $3  "  " $5 }}'
top -b -n1 | grep "Cpu(s)" | awk '{print 100 - $5}'
END
)"

This last option has the drawback of using more lines, but it doesn't require that you change anything on your commands.

Not the answer you're looking for? Browse other questions tagged or ask your own question.