繁体   English   中英

执行命令并将命令输出存储到变量

[英]execute commands and store command output to variable

该脚本从hosts.txt中读取系统IP,登录到系统,检查OS类型,执行一组命令并打印输出。

ssh部分工作正常,但是在显示“ ls”的输出后显示错误(没有这样的文件或目录)。

似乎/opt/hyperic/agent-current/bin/hq-agent.sh命令未在远程主机上执行。 目的是执行命令'cd / opt; ls,并在host.txt中提到的每个远程系统上捕获命令输出到STATUS。

当我在远程系统上手动运行命令时,返回以下输出。 对这里可能出什么问题有任何帮助吗?

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

在跑

脚本如下

#!/bin/bash
 while read host; do
 if ssh -o StrictHostKeyChecking=no -n root@$host '[ "$(awk "/CentOS/{print}" /etc/*release)" ] '
   then
    echo "(centos)"
    ssh -o StrictHostKeyChecking=no -n root@$host 'cd /opt;ls'
    STATUS=`/opt/hyperic/agent-current/bin/hq-agent.sh status | awk 'NR==1{print $3 $4}'`
   if [ "$STATUS" == "isrunning" ]
   then
      echo "$HOST == PASS"
   else
      echo "$HOST == FAIL"
  fi
  else
    echo "(generic)"
  fi
  done < hosts.txt

脚本的输出-

 root@10.10.1.1's password:
   firstboot
  puppet
  ./hq-enhanced.sh: line 14: /opt/hyperic/agent-current/bin/hq-agent.sh: No such file or   directory
  == FAIL

啊...我知道发生了什么事:

问题的关键是:

ssh -o StrictHostKeyChecking=no -n root@$host 'cd /opt;ls'
STATUS=`/opt/hyperic/agent-current/bin/hq-agent.sh status | awk 'NR==1{print $3 $4}'`

ssh命令立即运行并返回对脚本的控制权-此时,您不再通过ssh登录,并且无论您从何处运行脚本,都将以STATUS行开始执行。

要捕获ssh命令的输出,您将需要类似以下内容:

STATUS=`ssh root@foobar -c 'cd /foo/bar && /opt/hyperic/agent-current/bin/hq-agent.sh ...'`

HTH

暂无
暂无

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

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