【问题标题】:execute commands and store command output to variable执行命令并将命令输出存储到变量
【发布时间】:2014-03-20 09:51:12
【问题描述】:

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

ssh 部分工作正常,但是在显示 'ls'' 的输出后会显示错误(没有此类文件或目录)。

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

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

  ~]# /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

【问题讨论】:

    标签: bash shell unix


    【解决方案1】:

    啊……我明白发生了什么:

    问题的关键是:

    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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-11-09
      • 2015-09-11
      • 1970-01-01
      • 2011-12-31
      • 2011-12-11
      • 1970-01-01
      • 2012-04-03
      相关资源
      最近更新 更多