-1

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..

3 Answers3

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.

paulp
  • 31
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
Archemar
  • 31,554
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.