[ruby]获取zabbix上所有主机的ip
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)
# 输出
result['result'].each do |host|
host['interfaces'].each do |interfaces|
print "#{host['host']}: #{interfaces['ip']}\n"
end
end
本文作者:武平宁
本文链接:https://www.cnblogs.com/dewan/p/18623976
版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
2023-12-23 Linux: 自己动手写个命令行翻译程序
2023-12-23 Linux Shell: 写程序 背单词
2022-12-23 TCP 链接关闭 -- 客户端为什么需要60秒的time_wait状态