3

I try to ssh to multiple hosts (thousands of them), capture some command output and write in a file. But output of all command should be in same line, comma separated, space separated, anything but in same line for each host.

So my commands are like":

ssh $host "hostname; uname -r; echo mypassword| sudo -S ipmitool mc info | grep 'Firmware Revision' " > ssh.out

But if I use like this, it will write all command output to separate lines. (3 lines per host). But all I want is only one line per host, let's say:

myserver,3.2.45-0.6.wd.514,4.3 (comma or any field separator is fine)

How I can do this?

codeforester
  • 39,467
  • 16
  • 112
  • 140
JavaRed
  • 708
  • 4
  • 10
  • 34

3 Answers3

0

It's not very neat but using printf works. hostname and uname -r are verified to work. I don't know what ipmitool outputs so I can't verify it.

ssh $host "printf $(hostname),$(uname -r),$(echo mypassword| sudo -S ipmitool mc info | grep 'Firmware Revision')\n" > ssh.out
Eugene Chow
  • 1,688
  • 1
  • 11
  • 18
0

You can save the output of ssh into a variable and then print it:

ssh_output=$(ssh $host "hostname; uname -r; echo mypassword | sudo -S ipmitool mc info | grep 'Firmware Revision' ")
printf '%s\n' "$ssh_output"

codeforester
  • 39,467
  • 16
  • 112
  • 140
0

Use bash Array variables. Append the output of each ssh command to the array. At the end, echo all elements of the array. The result will be all array elements on a single line. Set IFS (the internal field separator) to desired per-host delimiter. (I used ,.) For handling multiple lines of output from multiple commands within the same ssh session, use tr to replace newlines with a delimiter. (I used a space.)

Code

sshoutput=()

for host in host01 host02 host03; do
    sshoutput+=($(ssh $host 'echo $(hostname; uname -a; echo mypassword) | tr "\n" " "'))
done

IFS=,; echo "${sshoutput[*]}";

Output

host01.domain.com Linux host01.domain.com 2.6.32-696.3.1.el6.x86_64 #1 SMP Thu Apr 20 11:30:02 EDT 2017 x86_64 x86_64 x86_64 GNU/Linux mypassword ,host02.domain.com Linux host02.domain.com 2.6.32-696.3.1.el6.x86_64 #1 SMP Thu Apr 20 11:30:02 EDT 2017 x86_64 x86_64 x86_64 GNU/Linux mypassword ,host03.domain.com Linux host03.domain.com 2.6.32-696.3.1.el6.x86_64 #1 SMP Thu Apr 20 11:30:02 EDT 2017 x86_64 x86_64 x86_64 GNU/Linux mypassword 
Chris Nauroth
  • 9,614
  • 1
  • 35
  • 39