JAVA访问Zabbix API
Zabbix
一、Zabbix 概述
zabbix是一个基于WEB界面的提供分布式系统监视以及网络监视功能的企业级的开源解决方案。zabbix能监视各种网络参数,保证服务器系统的安全运营;并提供灵活的通知机制以让系统管理员快速定位/解决存在的各种问题。
zabbix由2部分构成,zabbix server与可选组件zabbix agent。
(1)zabbix agent需要安装在被监视的目标服务器上,它主要完成对硬件信息或与操作系统有关的内存,CPU等信息的收集。
(2)zabbix server可以单独监视远程服务器的服务状态;同时也可以与zabbix agent配合,可以轮询zabbix agent主动接收监视数据(agent方式),同时还可被动接收zabbix agent发送的数据(trapping方式)。
二、Zabbix API
Zabbix的功能虽然很强大,能将数据以图表形式展现在Web中,但是,一个监控系统的使用者如果不了解Zabbix,或者其非维护人员需要通过监控了解各个服务器大致运行状况时,Zabbix所提供的界面就不是很友好了。
Zabbix API恰恰解决了这一问题。我们可以从API接口中读取想要了解的数据,用自己的方式展现在Web中。
三、java程序以HTTP方式向API请求数据
zabbix监控中的几个概念:
- hostid:每个被监控服务器唯一标识。可以根据ip/hostname获得,具体方法为代码中的getHostIdByIp/getHostIdByHostName。
- key:监控项名字,可以在zabbix平台自行查到。例如"system.cpu.util[,idle]","system.cpu.load[all,avg1]","system.swap.size[,free]"等等。
- itemid:根据hostid和key唯一缺确定,监控项的唯一标识。具体方法为代码中的getItemId(hostId, key)。
- value_type:数据类型,可以通过官方API item.get获取,history.get方法中就是传value_type给history参数。获取这个参数详见我代码中的方法getValueType(hostId, key),使用这个参数参考getHistoryDataByItemId(itemId, valueType, time_from, time_till)。具体参考:
https://www.zabbix.com/documentation/2.4/manual/api/reference/item/object
https://www.zabbix.com/documentation/2.4/manual/api/reference/history/get
package test.test;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
/**
* @author xueyuan@meizu.com
* @since 创建时间:2016年8月10日 上午11:43:49
*/
public class ZabbixUtil {
private static String URL = "http://IP:port/api_jsonrpc.php";
private static String AUTH = null;
private static final String USERNAME = "u";
private static final String PASSWORD = "p";
/**
* 向Zabbix发送Post请求,并返回json格式字符串
*
* @param param 请求参数
* @return
* @throws Exception
*/
private static String sendPost(Map map) {
String param = JSON.toJSONString(map);
HttpURLConnection connection = null;
DataOutputStream out = null;
BufferedReader reader = null;
StringBuffer sb = null;
try {
//创建连接
URL url = new URL(URL);
connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setUseCaches(false);
connection.setInstanceFollowRedirects(true);
connection.setRequestMethod("POST");
connection.setRequestProperty("Accept", "application/json"); // 设置接收数据的格式
connection.setRequestProperty("Content-Type", "application/json"); // 设置发送数据的格式
connection.connect();
//POST请求
out = new DataOutputStream(connection.getOutputStream());
out.writeBytes(param);
out.flush();
//读取响应
reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String lines;
sb = new StringBuffer("");
while ((lines = reader.readLine()) != null) {
lines = new String(lines.getBytes(), "utf-8");
sb.append(lines);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (out != null) {
try {
out.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (connection != null) {
connection.disconnect();
}
}
return sb.toString();
}
/**
* 通过用户名和密码设置AUTH,获得权限 @
*/
private static void setAuth() {
Map<String, Object> params = new HashMap<String, Object>();
params.put("user", USERNAME);
params.put("password", PASSWORD);
Map<String, Object> map = new HashMap<String, Object>();
map.put("jsonrpc", "2.0");
map.put("method", "user.login");
map.put("params", params);
map.put("auth", null);
map.put("id", 0);
String response = sendPost(map);
JSONObject json = JSON.parseObject(response);
AUTH = json.getString("result");
}
private static String getAuth() {
if (AUTH == null) {
setAuth();
}
return AUTH;
}
/**
* 获得主机hostid
*
* @param host Zabbix中配置的主机hosts
* @return 返回hostid @
*/
private static String getHostIdByHostName(String host) {
Map<String, Object> filter = new HashMap<String, Object>();
filter.put("host", host);
Map<String, Object> params = new HashMap<String, Object>();
params.put("output", "hostid");
params.put("filter", filter);
Map<String, Object> map = new HashMap<String, Object>();
map.put("jsonrpc", "2.0");
map.put("method", "host.get");
map.put("params", params);
map.put("auth", getAuth());
map.put("id", 0);
String response = sendPost(map);
JSONArray result = JSON.parseObject(response).getJSONArray("result");
if (result.size() > 0) {
JSONObject json = result.getJSONObject(0);
String hostid = json.getString("hostid");
return hostid;
} else {
return null;
}
}
/**
* 获得主机hostid
*
* @param host Zabbix中配置的主机hosts
* @return 返回hostid @
*/
private static String getHostIdByIp(String ip) {
Map<String, Object> filter = new HashMap<String, Object>();
filter.put("ip", ip);
Map<String, Object> params = new HashMap<String, Object>();
params.put("output", "extend");
params.put("filter", filter);
Map<String, Object> map = new HashMap<String, Object>();
map.put("jsonrpc", "2.0");
map.put("method", "host.get");
map.put("params", params);
map.put("auth", getAuth());
map.put("id", 0);
String response = sendPost(map);
JSONArray result = JSON.parseObject(response).getJSONArray("result");
if (result.size() > 0) {
JSONObject json = result.getJSONObject(0);
String hostId = json.getString("hostid");
return hostId;
} else {
return null;
}
}
/**
* 获得某主机的某个监控项id
*
* @param host 主机
* @param item 监控项
* @return 监控项itemid
* @throws Exception
*/
private static String getItemId(String hostId, String key) throws Exception {
JSONArray result = getItemByHostAndKey(hostId, key);
if (result.size() > 0) {
JSONObject json = result.getJSONObject(0);
if (json != null) {
return json.getString("itemid");
}
}
return null;
}
/**
* 获取某主机某监控项的value_type
*
* @param host
* @param key
* @return
* @throws Exception
* @author xueyuan@meizu.com
* @since 创建时间:2016年8月12日 上午10:38:10
*/
private static int getValueType(String hostId, String key) throws Exception {
JSONArray result = getItemByHostAndKey(hostId, key);
if (result.size() > 0) {
JSONObject json = result.getJSONObject(0);
if (json != null) {
return json.getIntValue("value_type");
}
}
return 3;
}
/**
* 获取某主机某监控项在一段时间内的数据
*
* @param itemId
* @param valueType
* @param from
* @param to
* @return
* @author xueyuan@meizu.com
* @since 创建时间:2016年8月18日 上午11:42:48
*/
public static JSONArray getHistoryDataByItemId(String itemId, int valueType, long from, long to) {
Map<String, Object> params = new HashMap<String, Object>();
params.put("output", "extend");
params.put("history", valueType);
params.put("itemids", itemId);
params.put("sortfield", "clock");
params.put("sortorder", "DESC");//时间降序
params.put("time_from", from / 1000);
params.put("time_till", to / 1000);
Map<String, Object> map = new HashMap<String, Object>();
map.put("jsonrpc", "2.0");
map.put("method", "history.get");
map.put("params", params);
map.put("auth", getAuth());
map.put("id", 0);
String response = sendPost(map);
JSONArray result = JSON.parseObject(response).getJSONArray("result");
return result;
}
/**
* 获取某主机某监控项最近的数据
*
* @param hostId
* @param key
* @return @
* @author xueyuan@meizu.com
* @since 创建时间:2016年8月12日 上午10:31:49
*/
public static JSONArray getItemByHostAndKey(String hostId, String key) {
if (hostId == null) {
return null;
}
Date start = new Date();
Map<String, Object> search = new HashMap<String, Object>();
search.put("key_", key);
Map<String, Object> params = new HashMap<String, Object>();
params.put("output", "extend");
params.put("hostids", hostId);
params.put("search", search);
Map<String, Object> map = new HashMap<String, Object>();
map.put("jsonrpc", "2.0");
map.put("method", "item.get");
map.put("params", params);
map.put("auth", getAuth());
map.put("id", 0);
String response = sendPost(map);
JSONArray result = JSON.parseObject(response).getJSONArray("result");
return result;
}
/**
* 多个监控项的当前数据
*
* @param itemIds
* @return
* @author xueyuan@meizu.com
* @since 创建时间:2016年8月18日 下午4:33:14
*/
public static JSONArray getDataByItems(List<String> itemIds) {
Map<String, Object> params = new HashMap<String, Object>();
params.put("output", "extend");
params.put("itemids", itemIds);
Map<String, Object> map = new HashMap<String, Object>();
map.put("jsonrpc", "2.0");
map.put("method", "item.get");
map.put("params", params);
map.put("auth", getAuth());
map.put("id", 0);
String response = sendPost(map);
JSONArray result = JSON.parseObject(response).getJSONArray("result");
return result;
}
/**
* 多个监控项的历史数据
*
* @param itemIds
* @param valueType
* @param from
* @param to
* @return
* @author xueyuan@meizu.com
* @since 创建时间:2016年8月18日 下午5:12:53
*/
public static JSONArray getHistoryDataByItems(List<String> itemIds, int valueType, long from,
long to) {
Map<String, Object> params = new HashMap<String, Object>();
params.put("output", "extend");
params.put("history", valueType);
params.put("itemids", itemIds);
params.put("sortfield", "clock");
params.put("sortorder", "DESC");//时间降序
params.put("time_from", from / 1000);
params.put("time_till", to / 1000);
Map<String, Object> map = new HashMap<String, Object>();
map.put("jsonrpc", "2.0");
map.put("method", "history.get");
map.put("params", params);
map.put("auth", getAuth());
map.put("id", 0);
String response = sendPost(map);
JSONArray result = JSON.parseObject(response).getJSONArray("result");
return result;
}
public static void main(String[] args) throws Exception {
setAuth();
long time_till = new Date().getTime();
long time_from = time_till - 5 * 60000;
String ip = "10.1.1.13";
String key = "system.cpu.util[,idle]";
String hostId = getHostIdByIp(ip);
String itemId = getItemId(hostId, key);
int valueType = getValueType(hostId, key);
getHistoryDataByItemId(itemId, valueType, time_from, time_till);
}
}
JAVA访问Zabbix API的更多相关文章
- 基于Zabbix API文档二次开发与java接口封装
(继续贴一篇之前工作期间写的经验案例) 一. 案例背景 我负责开发过一个平台的监控报警模块,基于zabbix实现,需要对zabbix进行二次开发. Zabbix官方提供了Rest ...
- salesforce 零基础学习(五十一)使用 Salesforce.com SOAP API 实现用户登录以及简单的增删改查(JAVA访问salesforce)
此篇请参看:https://resources.docs.salesforce.com/202/latest/en-us/sfdc/pdf/salesforce_developer_environme ...
- zabbix API应用
1.模拟登录 curl -i -X POST -H 'Content-Type:application/json' -d '{"jsonrpc":"2.0",& ...
- java 访问 usb
java 要访问 usb 设备,通常要自己写c/c++代码,然后再用 java 访问这些组件,以达到控制usb设备的目的.但现在有一个开源组件 libusb 帮我们做好了访问usb设备的封装(包括wi ...
- httpclient 认证方式访问http api/resutful api并获取json结果
最近,因公司线上环境rabbitmq经常发生堆积严重的现象,于是跟运维组讨论,帮助开发个集中监控所有rabbitmq服务器运行情况的应用,需要通过java访问rabbitmq暴露的http api并接 ...
- .Net程序员安卓学习之路2:访问网络API
做应用型的APP肯定是要和网络交互的,那么本节就来实战一把Android访问网络API,还是使用上节的DEMO: 一.准备API: 一般都采用Json作为数据交换格式,目前各种语言均能输出Json串. ...
- struts2 笔记01 登录、常用配置参数、Action访问Servlet API 和设置Action中对象的值、命名空间和乱码处理、Action中包含多个方法如何调用
Struts2登录 1. 需要注意:Struts2需要运行在JRE1.5及以上版本 2. 在web.xml配置文件中,配置StrutsPrepareAndExecuteFilter或FilterDis ...
- struts2访问servlet API
搭建环境: 引入jar包,src下建立struts.xml文件 项目配置文件web.xml. web.xml: <?xml version="1.0" encoding=&q ...
- Java访问USB设备
最近在用Java访问RDing设备,使用的是Java HID API.使用过程中发现一个问题,由于是嵌入式小白,不知道如何向USB设备发送report.于是想到可以看看自带的软件如何访问USB的.找到 ...
随机推荐
- [转帖]Dockerfile 中 ENTRYPOINT 与 CMD 的区别
Dockerfile 中 ENTRYPOINT 与 CMD 的区别 https://it.baiked.com/system/docker/1975.html 简单区别 Dockerfile 有两个启 ...
- Java时间处理
java.sql.PreparedStatement接口的setDate(int parameterIndex, java.sql.Date x)方法中的Date为java.sql包下的Date,而不 ...
- python的异常处理机制
异常机制己经成为衡量一门编程语言是否成熟的标准之一,使用异常处理机制的 Python 程序有更好的容错性,更加健壮. 对于计算机程序而言,情况就更复杂了一一没有人能保证自己写的程序永远不会出辛苦!就算 ...
- linux下selenium+phantomjs环境
# 安装依赖软件yum -y install wget fontconfig # 下载PhantomJSwget -P /tmp/ https://bitbucket.org/ariya/phanto ...
- Codeforces 1228E. Another Filling the Grid
传送门 看到 $n=250$ 显然考虑 $n^3$ 的 $dp$ 设 $f[i][j]$ 表示填完前 $i$ 行,目前有 $j$ 列的最小值是 $1$ 的合法方案数 那么对于 $f[i][j]$ ,枚 ...
- 解决maven依赖包下载慢的问题
修改maven 目录下setting.xml配置文件 在mirrors中添加如下配置即可 <mirror> <id>alimaven</id> <name&g ...
- X-Router软路由设置
一 内网: ip 192.168.0.1 掩码 255.255.255.0 网关 (空) DNS 202.96.128.68(佛山的)手动写入 二 外 ...
- 【原创】大数据基础之Logstash(6)mongo input
logstash input插件之mongodb是第三方的,配置如下: input { mongodb { uri => 'mongodb://mongo_server:27017/db' pl ...
- 查询SQL Server版本号
一.查看SQL Server 2005版本号 SELECT @@VERSION 显示以下信息: Microsoft SQL Server 2005 - 9.00.3042.00 (Intel X86) ...
- Java Jersey的详情概述
Jersey是一个RESTFUL请求服务JAVA框架,与常规的JAVA编程使用的struts框架类似,它主要用于处理业务逻辑层. 与springmvc 的区别: 1. jersey同样提供DI,是由g ...