我对 ruby 完全陌生,我正在尝试解析 XML 结构并过滤它以获取某些属性。XML 如下所示:
<systeminfo>
<machines>
<machine name="localhost">
<repository worker="localhost:8060" status="OK"/>
<dataengine worker="localhost:27042" status="OK"/>
<serverwebapplication worker="localhost:8000" status="OK"/>
<serverwebapplication worker="localhost:8001" status="OK"/>
<vizqlserver worker="localhost:9100" status="OK"/>
<vizqlserver worker="localhost:9101" status="OK"/>
<dataserver worker="localhost:9700" status="OK"/>
<dataserver worker="localhost:9701" status="OK"/>
<backgrounder worker="localhost:8250" status="OK"/>
<webserver worker="localhost:80" status="OK"/>
</machine>
</machines>
<service status="OK"/>
</systeminfo>
我想检查状态属性是否正常。到目前为止,我已经编写了这段代码:
#!/usr/bin/ruby -w
require 'rubygems'
require 'net/http'
require 'xmlsimple'
url = URI.parse("URL to XML")
req = Net::HTTP::Get.new(url.path)
res = Net::HTTP.start(url.host, url.port) {|http|
http.request(req)
}
sysinfodoc = XmlSimple.xml_in(res.body)
sysinfodoc["machines"][0]["machine"][0].each do |status|
p status[1][0]
p status[1][1]
end
输出:
{"worker"=>"localhost:8060", "status"=>"OK"}
nil
{"worker"=>"localhost:27042", "status"=>"OK"}
nil
{"worker"=>"localhost:9100", "status"=>"OK"}
{"worker"=>"localhost:9101", "status"=>"OK"}
{"worker"=>"localhost:8000", "status"=>"OK"}
{"worker"=>"localhost:8001", "status"=>"OK"}
{"worker"=>"localhost:8250", "status"=>"OK"}
nil
{"worker"=>"localhost:9700", "status"=>"OK"}
{"worker"=>"localhost:9701", "status"=>"OK"}
{"worker"=>"localhost:80", "status"=>"OK"}
nil
108
111
更新 输出应该是这样的:
OK
OK
OK
OK
OK
OK
OK
OK
OK
OK
该脚本应该与 nagios 一起使用。因此,我不想输出结果,而是想检查其中一个状态属性是否包含稍后不是“OK”的东西。 更新
如何摆脱 nils 和 fixnums?为什么还是有fixnums?
我怎样才能过滤这个,所以我只得到每个机器孩子的状态?或者这完全是错误的方法?