Ruby-MCollective:如何将命令的输出转换成Ruby变量(或对象)
我希望有人能在这方面帮助我,我正在写一个ruby脚本,我有一个问题。首先是大局: 当我从cli运行命令时:Ruby-MCollective:如何将命令的输出转换成Ruby变量(或对象),ruby,linux,puppet,Ruby,Linux,Puppet,我希望有人能在这方面帮助我,我正在写一个ruby脚本,我有一个问题。首先是大局: 当我从cli运行命令时: $ mco rpc puppet last_run_summary 我得到这个输出: epuppet01.example.com Changed Resources: 0 Config Retrieval Time: 1.21247005462646 Config Version: 137717
$ mco rpc puppet last_run_summary
我得到这个输出:
epuppet01.example.com
Changed Resources: 0
Config Retrieval Time: 1.21247005462646
Config Version: 1377176819
Failed Resources: 1
Last Run: 1377241107
Out of Sync Resources: 1
Since Last Run: 195
Summary: {"events"=>{"total"=>1, "success"=>0, "failure"=>1},
"resources"=>
{"scheduled"=>0,
"total"=>8,
"skipped"=>7,
"out_of_sync"=>1,
"failed"=>1,
"changed"=>0,
"failed_to_restart"=>0,
"restarted"=>0},
"changes"=>{"total"=>0},
"version"=>{"config"=>1377176819, "puppet"=>"3.1.1"},
"time"=>
{"config_retrieval"=>1.21247005462646,
"total"=>1.85353105462646,
"last_run"=>1377241107,
"package"=>0.641061}}
Total Resources: 8
Total Time: 1.85353105462646
Type Distribution: {"Package"=>1}
我想要的是将该命令的输出重定向/获取到某个变量/对象中。具体来说,我想从摘要中获取“失败的资源”部分或“失败的”值
有什么想法吗?a怎么能这么做
到目前为止,代码如下所示:
def runSingle
cmd = []
cmd.push(which("mco", ["/usr/bin", "/opt/puppet/bin"]))
shell_command(cmd + ["rpc", "puppet", " last_run_summary", "-I"] + shell_escaped_nodes)
end
谢谢 您可以这样更改代码:
def runSingle
cmd = []
cmd.push(which("mco", ["/usr/bin", "/opt/puppet/bin"]))
cmd_output = shell_command(cmd + ["rpc", "puppet", " last_run_summary", "-I"] + shell_escaped_nodes)
result = cmd_failure_stats(cmd_output)
# you'll get 'result' as Ruby hash, like:
# {
# :failed_resources => "1",
# :summary_failed => "1"
# }
# from which you can access desired values as:
# result[:failed_resources] #=> "1"
end
def cmd_failure_stats(raw_string)
return_result = {}
raw_string.lines.map do |line|
return_result[:failed_resources] = line[/Failed Resources.*([\d]+)/, 1] if line[/(Failed Resources.*[\d]+)/, 1]
return_result[:summary_failed] = line[/failed\".*=>([\d]+)/, 1] if line[/failed\".*=>([\d]+)/, 1] }
end
return_result
end