简体   繁体   English

从多个shell命令的输出创建单行

[英]Creating a single line from output of multiple shell commands

I try to ssh to multiple hosts (thousands of them), capture some command output and write in a file. 我尝试ssh到多个主机(数千个),捕获一些命令输出并写入文件。 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). (每个主机3行)。 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? 我怎么能这样做?

It's not very neat but using printf works. 它不是很整洁,但使用printf工作。 hostname and uname -r are verified to work. 验证hostnameuname -r是否有效。 I don't know what ipmitool outputs so I can't verify it. 我不知道ipmitool输出什么,所以我无法验证它。

ssh $host "printf $(hostname),$(uname -r),$(echo mypassword| sudo -S ipmitool mc info | grep 'Firmware Revision')\n" > ssh.out

You can save the output of ssh into a variable and then print it: 您可以将ssh的输出保存到变量中,然后将其打印出来:

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

Use bash Array variables . 使用bash 数组变量 Append the output of each ssh command to the array. 将每个ssh命令的输出附加到数组。 At the end, echo all elements of the array. 最后, echo显数组的所有元素。 The result will be all array elements on a single line. 结果将是所有数组元素在一行上。 Set IFS (the internal field separator) to desired per-host delimiter. IFS (内部字段分隔符)设置为所需的每个主机分隔符。 (I used , .) For handling multiple lines of output from multiple commands within the same ssh session, use tr to replace newlines with a delimiter. (我用过, 。)为了处理同一个ssh会话中多个命令的多行输出,使用tr用分隔符替换换行符。 (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 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM