get_zabbix_hosts.rb
require 'net/http'
require 'uri'
require 'json'
require 'yaml'
# 加载配置文件
config = YAML.load_file('config.yml')
url = config['credentials']['url']
def get_token(config, url)
user = config['credentials']['user']
password = config['credentials']['password']
uri = URI(url)
header = { 'Content-Type' => 'application/json-rpc' }
body = {
jsonrpc: "2.0",
method: "user.login",
params: {
user: user,
password: password
},
id: 0,
auth: nil
}.to_json
response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') do |http|
request = Net::HTTP::Post.new(uri, header)
request.body = body
http.request(request)
end
result = JSON.parse(response.body)
result['result']
end
token = get_token(config, url)
uri = URI(url)
header = { 'Content-Type' => 'application/json-rpc' }
body = {
jsonrpc: "2.0",
method: "host.get",
params: {
output: ["hostid", "host"],
selectInterfaces: ["interfaceid", "ip"]
},
id: 2,
auth: token
}.to_json
response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') do |http|
request = Net::HTTP::Post.new(uri, header)
request.body = body
http.request(request)
end
result = JSON.parse(response.body)
#puts result
#
if result['result']
result['result'].each do |host|
if host['interfaces']
host['interfaces'].each do |interfaces|
puts interfaces['ip']
end
end
end
end
标签:body,end,ip,request,uri,zabbix,result,config,ruby
From: https://www.cnblogs.com/dewan/p/18623976