繁体   English   中英

将命令输出存储在变量中

[英]store command output in variable

我正在研究一个脚本,该脚本对几个系统(在lab.txt中列出)执行ssh,运行两个命令,将命令的输出存储在两个不同的变量中并打印它们。

这是使用的脚本:

#!/bin/bash

while read host; do

ssh -n root@$host "$(STATUS=$(awk 'NR==1{print $1}' /etc/*release)  \
OS=$(/opt/agent/bin/agent.sh status | awk 'NR==1{print $3 $4}'))"

echo $STATUS
echo $OS

done < lab.txt

lab.txt文件包含一些我需要登录,执行和打印命令输出的Ips。

~#] cat lab.txt
192.168.1.1
192.168.1.2

执行脚本时,显示ssh登录提示符192.168.1.1,输入密码后,输出显示为空白。 与下一个IP 192.168.1.2相同

当我在192.168.1.1内手动执行这些命令时,将返回以下内容。

~]# awk 'NR==1{print $1}' /etc/*release        
    CentOS

~]# /opt/agent/bin/agent.sh status | awk 'NR==1{print $3 $4}'
    isrunning

该脚本可能有什么问题? 有更好的方法吗?

就像评论所说,您正在服务器端在bash会话内设置变量,并尝试从客户端读取它们。

如果要在客户端脚本中分配变量,则需要将分配放在ssh命令的前面,并将两个分配分开。 类似于以下内容。

STATUS=`ssh -n root@$host 'awk \'NR==1{print $1}\' /etc/*release)`
OS=`ssh -n root@$host '/opt/agent/bin/agent.sh status | awk \'NR==1{print $3 $4}\''`

您需要执行两个ssh命令。 如果在客户端而不是服务器上运行awk ,这也会简化操作,因为ssh命令中的引用会变得很复杂。

while read host; do
    STATUS=$(ssh -n root@$host 'cat /etc/*release' | awk 'NR==1{print $1}')
    OS=$(ssh -n root@$host /opt/agent/bin/agent.sh status | awk 'NR==1{print $3 $4}')
    echo $STATUS
    echo $OS
done < lab.txt

用一条ssh语句:

read STATUS OS < <(ssh -n root@$host "echo \ 
                  \$(awk 'NR==1{print \$1}' /etc/*release) \
                  \$(/opt/agent/bin/agent.sh status | awk 'NR==1{print \$3 \$4}')")
echo $STATUS
echo $OS

说明:

<(命令)语法称为流程替换 您可以在需要文件的任何地方使用它。

例:

sdiff <(echo -e "1\n2\n3") <(echo -e "1\n3")

命令sdiff需要两个文件作为参数。 使用流程替换语法,您可以将命令用作参数。 (例如,伪造文件)

暂无
暂无

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

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