1. Java对接Zabbix API 前提准备
zabbix对接文档地址: https://www.zabbix.com/documentation/6.4/zh/manual/api
对接Zabbix API接口需要针对对接的用户授予对应的API权限,如下图所示
- 使用超管账户登录zabbix
- 用户---> 用户,查看用户列表
- 点击对接的用户 ctj-jiankong,查看用户权限-->API
- API权限分为用户权限和角色权限
- 角色权限高于用户权限
- 例如 用户 张三 的角色是 visitor,用户API权限是所有,角色API权限是 只拥有XX权限,那么综合起来张三的API权限只是 XX
- 如下图所示 就对应了用户(ctj-jiankong)API权限和角色(User Role)API权限不一致的场景,导致用户调用API报错没有权限
2. Zabbix API 常量定义
/** * @author : test * @className : ZabbixAPiConstant * @description : 描述说明该类的功能 * @date : 2024/2/27 15:05 */ public interface ZabbixAPiConstant { /** * 主机获取 */ String HOST_GET_URL = "host.get"; /** * 主机监控项获取 */ String HOST_MONITOR_ITEMS_GET_URL = "item.get"; /** * 主机监控项值获取 */ String HOST_MONITOR_ITEM_VALUE_GET_URL = "history.get"; /** * 登录 */ String USER_LOGIN_URL = "user.login"; /** * Auth验证 */ String AUTH_CHECK_URL= "user.checkAuthentication"; /** * 获取版本信息 */ String ZABBIX_VERSION_GET_URL = "apiinfo.version"; /** * 告警获取 */ String ALARM_RUL = "alert.get"; /** * 主机组获取 */ String HOST_GROUP = "hostgroup.get"; /** * 事件获取 */ String EVENT_URL = "event.get"; /** * 查询接口常数 */ String ZABBIX_QUERY_FILTER = "filter"; String ZABBIX_QUERY_HOSTIDS = "hostids"; String ZABBIX_QUERY_ITEMIDS= "itemids"; String ZABBIX_QUERY_OUTPUT = "output"; String ZABBIX_QUERY_EXTEND = "extend"; String ZABBIX_QUERY_NAME = "name"; String ZABBIX_QUERY_SORTORDER = "sortorder"; String ZABBIX_QUERY_DESC = "DESC"; String ZABBIX_QUERY_HISTORY = "history"; String ZABBIX_QUERY_LIMIT = "limit"; String ZABBIX_QUERY_SORTFIELD = "sortfield"; String ZABBIX_QUERY_CLOCK = "clock"; String ZABBIX_QUERY_IP = "ip"; String ZABBIX_AUTH_USERNAME = "username"; String ZABBIX_AUTH_PASSWORD = "password"; String ZABBIX_RESPONSE_RESULT = "result"; String ZABBIX_ALARM_ACTIONIDS = "actionids"; String ZABBIX_ALARM_JSONRPC = "jsonrpc"; String ZABBIX_ALARM_TIME_FROM = "time_from"; String ZABBIX_ALARM_TIME_Till = "time_till"; String ZABBIX_ALARM_GROUPID = "groupids"; String ZABBIX_ALARM_SELECT_HOSTS = "selectHosts"; String ZABBIX_PARAMS = "params"; }
3. 对接Zabbix参数配置定义
import lombok.Data; import lombok.extern.slf4j.Slf4j; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.stereotype.Component; /** * @author : test * @className : ZabbixConfig * @description : 描述说明该类的功能 * @date : 2024/2/26 14:52 */ @Component @ConfigurationProperties(prefix = "zabbix.config") @Data @Slf4j public class ZabbixConfig { private String url; private String username; private String password; private volatile ZabbixApi zabbixApi; /** * 獲取API * @return */ public ZabbixApi getZabbixApi() { if (null == zabbixApi) { synchronized (ZabbixConfig.class) { if (null == zabbixApi) { zabbixApi = new DefaultZabbixApi(getUrl()); zabbixApi.init(); login(); } } } return zabbixApi; } /** * 登錄 */ public void login(){ boolean login = zabbixApi.login(getUsername(),getPassword()); if(!login){ throw new RuntimeException("zabbix login failed!"); } log.info("zabbix login success!"); } /** * zabbix判断登录是否失效 * @return */ public boolean loginIsExpire(){ return zabbixApi.checkAuthExpired(); } }
zabbix: config: url: http://127.0.0.1:12345/api_jsonrpc.php username: admin password: admin@1234
4. 对接Zabbix请求参数定义
如上图所示,在跟Zabbix API对接时,一般使用到五个请求参数(jsonrpc、method、params、auth、id),因此根据该种情况定义如下参数请求类Request以及其建造者模式RequestBuilder
@Data public class Request { /** * jsonrpc协议版本 */ private String jsonrpc = "2.0"; /** * 请求参数实体类 */ private Map<String, Object> params = new HashMap<>(); /** * 请求方式-post/get */ private String method; /** * auth认证信息 */ private String auth; /** * 随机id */ private Integer id; /** * 添加请求参数 * @param key * @param value */ public void putParam(String key, Object value) { params.put(key, value); } }
5. 对接Zabbix请求参数创建器定义
import java.util.concurrent.atomic.AtomicInteger; public class RequestBuilder { private static final AtomicInteger nextId = new AtomicInteger(1); private Request request = new Request(); private RequestBuilder(){ } static public RequestBuilder newBuilder(){ return new RequestBuilder(); } public Request build(){ if(request.getId() == null){ request.setId(nextId.getAndIncrement()); } return request; } public RequestBuilder version(String version){ request.setJsonrpc(version); return this; } public RequestBuilder paramEntry(String key, Object value){ request.putParam(key, value); return this; } public RequestBuilder auth(String auth){ request.setAuth(auth); return this; } public RequestBuilder method(String method){ request.setMethod(method); return this; } public RequestBuilder jsonrpc(String jsonrpc){ request.setJsonrpc(jsonrpc); return this; } public RequestBuilder id(Integer id){ request.setId(id); return this; } }
6. 对接Zabbix基础接口定义
定义我们经常使用的对接Zabbix PI的方法
import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import java.util.List; import java.util.Set; public interface ZabbixApi { void init(); void destroy(); String apiVersion(); JSONObject call(Request request,boolean auth); boolean login(String user, String password); List<Host> hostList(); List<Host> hostListByIp(List<String> ips); List<Host> hostListByName(String name); List<Item> hostMonitorItems(String hoistId); ItemValue hostMonitorItemLastValue(String itemId, Integer history); JSONArray getAlarmDataObtaining(Integer actionsId, String timeFrom); cn.hutool.json.JSONArray getEventAlarm(String timeFrom, String timeTill); boolean checkAuthExpired(); List<ItemValue> getHostSpecItemsLastValueCollection(String hostId, Set<String> itemIds, String valueType); }
7. 对接Zabbix接口实现定义
import cn.hutool.core.collection.CollectionUtil; import cn.hutool.json.JSONUtil; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject;import org.apache.commons.lang3.StringUtils; import org.apache.http.HttpEntity; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpUriRequest; import org.apache.http.entity.ContentType; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.util.EntityUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import java.util.*; import java.util.stream.Collectors; public class DefaultZabbixApi implements ZabbixApi { private static final Logger logger = LoggerFactory.getLogger(DefaultZabbixApi.class); private CloseableHttpClient httpClient; private URI uri; private volatile String auth; public DefaultZabbixApi(String url) { try { uri = new URI(url.trim()); } catch (URISyntaxException e) { throw new RuntimeException("url invalid", e); } } @Override public void init() { if (httpClient == null) { httpClient = HttpClients.custom().build(); } } @Override public void destroy() { if (httpClient != null) { try { httpClient.close(); } catch (Exception e) { logger.error("close httpclient error!", e); } } } /** * 检验auth是否过期 * @return */ @Override public boolean checkAuthExpired() { if (StringUtils.isEmpty(this.auth)) { return true; } Request request = RequestBuilder.newBuilder() .paramEntry("sessionid", this.auth) .method(AUTH_CHECK_URL) .id((int) (Math.random() * 1000)) .auth(this.auth) .jsonrpc("2.0").build(); JSONObject result = call(request, false); if (null != result.get("result")) { return false; } return true; } @Override public boolean login(String user, String password) { this.auth = null; Request request = RequestBuilder.newBuilder() .paramEntry(ZABBIX_AUTH_USERNAME, user) .paramEntry(ZABBIX_AUTH_PASSWORD, password) .method(USER_LOGIN_URL) .id(1) .auth(null) .jsonrpc("2.0").build(); JSONObject response = call(request, false); String auth = response.getString(ZABBIX_RESPONSE_RESULT); if (auth != null && !auth.isEmpty()) { this.auth = auth; return true; } return false; } /** * 获取API 版本 * @return */ @Override public String apiVersion() { Request request = RequestBuilder.newBuilder().method(ZABBIX_VERSION_GET_URL).build(); JSONObject response = call(request, false); return response.getString(ZABBIX_RESPONSE_RESULT); } /** * 主機列表 * * @return groupId */ @Override public List<Host> hostList() { Request request = RequestBuilder.newBuilder() .method(HOST_GET_URL) .build(); JSONObject response = call(request, true); return getHosts(response); } /** * 根据ip查询 * * @param ips * @return */ @Override public List<Host> hostListByIp(List<String> ips) { JSONObject filter = new JSONObject(); filter.put(ZABBIX_QUERY_IP, ips); Request request = RequestBuilder.newBuilder() .method(HOST_GET_URL) .paramEntry(ZABBIX_QUERY_FILTER, filter) .build(); JSONObject response = call(request, true); return getHosts(response); } /** * 组装我们定义的实体类 * @param response * @return */ private static List<Host> getHosts(JSONObject response) { JSONArray jsonArray = response.getJSONArray(ZABBIX_RESPONSE_RESULT); List<Host> hosts = new ArrayList<>(); for (int i = 0; i < jsonArray.size(); i++) { JSONObject jsonObject = jsonArray.getJSONObject(i); Set<String> keySet = jsonObject.keySet(); JSONObject jsonObjectNew = new JSONObject(); for (String s : keySet) { String f = com.baomidou.mybatisplus.core.toolkit.StringUtils.underlineToCamel(s); jsonObjectNew.put(f, jsonObject.get(s)); } Host host = jsonObjectNew.toJavaObject(Host.class); hosts.add(host); } return hosts; } /** * 根据名称查询 * * @param name * @return */ @Override public List<Host> hostListByName(String name) { JSONObject filter = new JSONObject(); filter.put(ZABBIX_QUERY_NAME, Arrays.asList(name)); Request request = RequestBuilder.newBuilder() .method(HOST_GET_URL) .paramEntry(ZABBIX_QUERY_FILTER, filter) .build(); JSONObject response = call(request, true); return getHosts(response); } /** * 获取指定主机的监控项信息 * * @param hoistId * @return */ @Override public List<Item> hostMonitorItems(String hoistId) { Request request = RequestBuilder.newBuilder() .method(HOST_MONITOR_ITEMS_GET_URL) .paramEntry(ZABBIX_QUERY_OUTPUT, ZABBIX_QUERY_EXTEND) .paramEntry(ZABBIX_QUERY_HOSTIDS, hoistId) .build(); JSONObject response = call(request, true); JSONArray jsonArray = response.getJSONArray(ZABBIX_RESPONSE_RESULT); List<Item> items = new ArrayList<>(); for (int i = 0; i < jsonArray.size(); i++) { JSONObject jsonObject = jsonArray.getJSONObject(i); Set<String> keySet = jsonObject.keySet(); JSONObject jsonObjectNew = new JSONObject(); for (String s : keySet) { String f = com.baomidou.mybatisplus.core.toolkit.StringUtils.underlineToCamel(s); jsonObjectNew.put(f, jsonObject.get(s)); } Item item = jsonObjectNew.toJavaObject(Item.class); items.add(item); } return items; } /** * 获取指定主机+指定类型+指定监控项集合——>最新数据集合 * @param hostId * @param itemIds * @param valueType * @return */ @Override public List<ItemValue> getHostSpecItemsLastValueCollection(String hostId,Set<String> itemIds,String valueType) { Request request = RequestBuilder.newBuilder() .method(HOST_MONITOR_ITEM_VALUE_GET_URL) .paramEntry(ZABBIX_QUERY_OUTPUT, ZABBIX_QUERY_EXTEND) .paramEntry(ZABBIX_QUERY_HOSTIDS, hostId) .paramEntry(ZABBIX_QUERY_HISTORY, valueType) .paramEntry(ZABBIX_QUERY_SORTORDER, ZABBIX_QUERY_DESC) .paramEntry(ZABBIX_QUERY_SORTFIELD, ZABBIX_QUERY_CLOCK) .build(); JSONObject response = call(request, true); if(response.isEmpty()){ return null; } Map<String,ItemValue> itemValueMap = new HashMap<>(); try{ JSONArray jsonArray = response.getJSONArray(ZABBIX_RESPONSE_RESULT); if(CollectionUtil.isNotEmpty(jsonArray)){ jsonArray.parallelStream().forEach( e -> { cn.hutool.json.JSONObject jsonObject = JSONUtil.parseObj(e); Set<String> keySet = jsonObject.keySet(); JSONObject jsonObjectNew = new JSONObject(); for (String s : keySet) { String f = com.baomidou.mybatisplus.core.toolkit.StringUtils.underlineToCamel(s); jsonObjectNew.put(f,jsonObject.get(s)); } ItemValue itemValue = jsonObjectNew.toJavaObject(ItemValue.class); String itemid = itemValue.getItemid(); String ns = itemValue.getNs(); if(itemValueMap.containsKey(itemid)){ ItemValue itemValue1 = itemValueMap.get(itemid); String ns1 = itemValue1.getNs(); if(Long.parseLong(ns1) > Long.parseLong(ns)){ itemValueMap.put(itemid,itemValue); } }else{ itemValueMap.put(itemid,itemValue); } } ); } }catch (Exception e){ logger.error(e.getMessage(),e); } return itemValueMap.values().stream().collect(Collectors.toList()); } /** * 获取指定主机的指定监控项最新数据 * * @param itemId 监控项id * @param history 监控项值类型(value_type 值) * 0 - 浮点型; * 1 - 字符; * 2 - 日志; * 3 - 无符号数字; * 4 - 文本。 * @return */ @Override public ItemValue hostMonitorItemLastValue(String itemId, Integer history) { int limit = 1; Request request = RequestBuilder.newBuilder() .method(HOST_MONITOR_ITEM_VALUE_GET_URL) .paramEntry(ZABBIX_QUERY_OUTPUT, ZABBIX_QUERY_EXTEND) .paramEntry(ZABBIX_QUERY_ITEMIDS, itemId) .paramEntry(ZABBIX_QUERY_SORTORDER, ZABBIX_QUERY_DESC) .paramEntry(ZABBIX_QUERY_HISTORY, String.valueOf(history.intValue())) .paramEntry(ZABBIX_QUERY_SORTFIELD, ZABBIX_QUERY_CLOCK) .paramEntry(ZABBIX_QUERY_LIMIT, limit) .build(); /** md history==1==limit时会报这个错误,解决方案: 将history置为String类型 * { * "auth": "30d4a1696e51e43c2e587da46169c638", * "id": 335, * "jsonrpc": "2.0", * "method": "history.get", * "params": { * "history": { * "$ref": "limit" * }, * "itemids": "802549", * "limit": 1, * "output": "extend", * "sortfield": "clock", * "sortorder": "DESC" * } * } */ JSONObject response = call(request, true); try{ JSONArray jsonArray = response.getJSONArray(ZABBIX_RESPONSE_RESULT); if(CollectionUtil.isNotEmpty(jsonArray)){ JSONObject jsonObject = jsonArray.getJSONObject(0); Set<String> keySet = jsonObject.keySet(); JSONObject jsonObjectNew = new JSONObject(); for (String s : keySet) { String f = com.baomidou.mybatisplus.core.toolkit.StringUtils.underlineToCamel(s); jsonObjectNew.put(f,jsonObject.get(s)); } ItemValue itemValue = jsonObjectNew.toJavaObject(ItemValue.class); return itemValue; } }catch (Exception e){ logger.error(e.getMessage(),e); } return new ItemValue(); } /** * 告警数据获取 * * @param actionsId 告警动作id * @param timeFrom 时间戳,返回这个时间段以后的数据 * @return */ @Override public JSONArray getAlarmDataObtaining(Integer actionsId, String timeFrom) { List<HostGroupDTO> hostGroupDTOList = JSONUtil.toList(getHostGroup(), HostGroupDTO.class); List<String> groupList = hostGroupDTOList.stream().filter(x -> x.getName().contains("-政务云")).map(x -> x.getGroupid()).collect(Collectors.toList()); Request request = RequestBuilder.newBuilder() .method(ALARM_RUL) .jsonrpc("2.0") .paramEntry(ZABBIX_QUERY_OUTPUT, "extend") .paramEntry(ZABBIX_ALARM_ACTIONIDS, actionsId) .paramEntry(ZABBIX_ALARM_TIME_FROM, timeFrom) .paramEntry(ZABBIX_ALARM_GROUPID, (groupList.size() > 0 ? groupList.stream().toArray(String[]::new) : null)) .id(1) .build(); JSONObject response = call(request, true); return response.getJSONArray(ZABBIX_RESPONSE_RESULT); } /** * 获取主机群组全部信息 * * @return */ private cn.hutool.json.JSONArray getHostGroup() { Request request = RequestBuilder.newBuilder() .method(HOST_GROUP) .jsonrpc("2.0") .paramEntry(ZABBIX_QUERY_OUTPUT, "extend") .id(1) .build(); JSONObject response = call(request, true); String jsonArray = response.getString(ZABBIX_RESPONSE_RESULT); cn.hutool.json.JSONArray array = JSONUtil.parseArray(jsonArray); return array; } /** * 底层对接Zabbix API * @param request * @param auth * @return */ @Override public JSONObject call(Request request,boolean auth) { if (request.getAuth() == null && auth) { request.setAuth(this.auth); } if(!auth){ request.setAuth(null); } try { HttpUriRequest httpRequest = org.apache.http.client.methods.RequestBuilder.post().setUri(uri) .addHeader("Content-Type", "application/json") .setEntity(new StringEntity(JSON.toJSONString(request), ContentType.APPLICATION_JSON)).build(); CloseableHttpResponse response = httpClient.execute(httpRequest); HttpEntity entity = response.getEntity(); byte[] data = EntityUtils.toByteArray(entity); String str = new String(data); if(StringUtils.isBlank(str) || StringUtils.isEmpty(str)){ return new JSONObject(); } return (JSONObject) JSON.parse(str); } catch (IOException e) { throw new RuntimeException("DefaultZabbixApi call exception!", e); } } /** * 获取告警信息 * @param timeFrom * @param timeTill * @return */ @Override public cn.hutool.json.JSONArray getEventAlarm(String timeFrom, String timeTill) { List<HostGroupDTO> hostGroupDTOList = JSONUtil.toList(getHostGroup(), HostGroupDTO.class); List<String> groupList = hostGroupDTOList.stream().filter(x -> x.getName().contains("-政务云")).map(x -> x.getGroupid()).collect(Collectors.toList()); Request request = RequestBuilder.newBuilder() .method(EVENT_URL) .jsonrpc("2.0") .paramEntry(ZABBIX_QUERY_OUTPUT, "extend") .paramEntry(ZABBIX_QUERY_SORTFIELD, "clock") .paramEntry(ZABBIX_QUERY_SORTORDER, "DESC") .paramEntry(ZABBIX_ALARM_TIME_FROM, timeFrom) .paramEntry(ZABBIX_ALARM_TIME_Till, timeTill) .paramEntry(ZABBIX_ALARM_GROUPID, (groupList.size() > 0 ? groupList.stream().toArray(String[]::new) : null)) .paramEntry(ZABBIX_ALARM_SELECT_HOSTS, new String[]{"host"}) .id(1) .build(); JSONObject response = call(request, true); return JSONUtil.parseArray(response.getString(ZABBIX_RESPONSE_RESULT)); } }
8. 其他实体类定义
import lombok.Data; /** * 主机信息 */ @Data public class Host { /** * 主机的ID. */ private String hostid; /** * 用于监控主机的Proxy ID。 */ private String proxyHostid; /** * 正式名称 */ private String host; /** * 主机的状态和功能。 * * 可能的值是: * 0 - (默认) 开启监控的主机; * 1 - 没有开启监控的主机。 */ private String status; /** *不可用状态Agent的下一次轮训时间. */ private String disableUntil; /** * Agent不可用时的错误信息 */ private String error; /** * Agent不可用时的时间. */ private String available; /** * 主机的来源. * * 可能的值: * 0 - 普通主机; * 4 - 自动发现的主机. */ private String errorsFrom; private String lastaccess; /** * MI 认证算法. * * 可能的值: * -1 - (默认) 默认; * 0 - 无; * 1 - MD2; * 2 - MD5 * 4 - straight; * 5 - OEM; * 6 - RMCP+ */ private String ipmiAuthtype; /** * MI 权限等级. * * 可能的值: * 1 - 回调; * 2 - (默认) 用户; * 3 - 操作员; * 4 - 管理员; * 5 - OEM原厂. */ private String ipmiPrivilege; /** * IPMI 用户名. */ private String ipmiUsername; /** * IPMI 密码。 */ private String ipmiPassword; /** * 不可用状态IPMI agent的下一次轮训时间. */ private String ipmiDisableUntil; private String ipmiAvailable; private String snmpDisableUntil; private String snmpAvailable; private String maintenanceid; private String maintenanceStatus; private String maintenanceType; private String maintenanceFrom; private String ipmiErrorsFrom; private String snmpErrorsFrom; private String ipmiError; private String snmpError; private String jmxDisableUntil; private String jmxAvailable; private String jmxErrorsFrom; private String jmxError; private String name; private String flags; private String templateid; private String description; private String tlsConnect; private String tlsAccept; private String tlsIssuer; private String tlsSubject; private String tlsPskIdentity; private String tlsPsk; private String proxyAddress; private String autoCompress; }
import lombok.Data; /** * 主机监控项 */ @Data public class Item { /** * 监控项ID。 */ private String itemid; /** * 监控项类型。 * * 可用值: * 0 - Zabbix agent; * 2 - zabbix 采集器; * 3 - 简单检查; * 5 - 内部检查; * 7 - Zabbix agent (主动); * 9 - web 监控项; * 10 - 外部检查; * 11 - 数据库监控; * 12 - IPMI agent; * 13 - SSH agent; * 14 - Telnet agent; * 15 - 可计算的监控; * 16 - JMX agent; * 17 - SNMP trap; * 18 - 相关项监控; * 19 - HTTP agent; * 20 - SNMP agent; * 21 - 脚本。 */ private String type; /** *仅用于SNMPv1 and SNMPv2 监控项。 */ private String snmpCommunity; /** * SNMP OID */ private String snmpOid; /** *监控项所属的主机或模板的 ID。 */ private String hostid; /** * 监控项名称。 */ private String name; /** *监控项关键字。 */ private String key_; /** * 更新监控项的时间间隔 */ private String delay; /** *历史数据应保留多长时间的单位。同样接受用户宏。 * * 默认: 90天。 */ private String history; /** * 趋势数据应保留多长时间的单位。可接受用户宏。 * * 默认:365天。 */ private String trends; /** * 监控项状态。 * * 可用值: * 0 - (默认) 启用监控项; * 1 - 禁用监控项。 */ private String status; /** * 监控项数据类型 * * 可用值: * 0 - 浮点型; * 1 - 字符; * 2 - 日志; * 3 - 无符号数字; * 4 - 文本。 */ private String valueType; /** *允许的主机。采集器监控项或 HTTP agent 监控项使用。 */ private String trapperHosts; /** *值的单位。 */ private String units; /** *SNMPv3安全名称。仅用于SNMPv3监控项 */ private String snmpv3Securityname; /** * SNMPv3安全等级。仅用于SNMPv3监控项。 * * Possible values: * 0 - noAuthNoPriv; * 1 - authNoPriv; * 2 - authPriv. */ private String snmpv3Securitylevel; /** * SNMPv3认证密码。仅用于SNMPv3监控项。 */ private String snmpv3Authpassphrase; /** * SNMPv3私钥。仅用于SNMPv3监控项。 */ private String snmpv3Privpassphrase; /** * */ private String formula; /** * 当更新监控项出错时的错误文本 */ private String error; /** * */ private String lastlogsize; /** * 日志条目的时间格式。仅用于日志监控项。 */ private String logtimefmt; /** *只读)父模板的ID。 */ private String templateid; /** *关联映射值的ID。 */ private String valuemapid; /** *取决于监控项类型的附加参数: * - executed script for SSH and Telnet items; * - SQL query for database monitor items; * - formula for calculated items. */ private String params; /** * IPMI传感器。仅用于IPMI监控项。 */ private String ipmiSensor; /** * 仅在SSH agent items or HTTP agent items中使用。 * * SSH agent authentication method possible values: * 0 - (default) password; * 1 - public key. * * HTTP agent authentication method possible values: * 0 - (default) none * 1 - basic * 2 - NTLM */ private String authtype; /** *认证的用户名。用于simple check, SSH, Telnet, database monitor, JMX and HTTP agent 监控项。 */ private String username; /** *认证的密码 */ private String password; /** *公钥的文件名。 */ private String publickey; /** * 私钥文件名。 */ private String privatekey; /** * . 被监控的日志文件最后一次被更新的时间。仅泳衣日志监控项。 */ private String mtime; /** * (readonly) Origin of the item. * * Possible values: * 0 - a plain item; * 4 - a discovered item. */ private String flags; /** *监控项主机接口的ID。 仅用于主机项。 */ private String interfaceid; /** *监控项监控的端口。仅用于SMNP监控项 */ private String port; /** *监控项说明。 */ private String description; /** *. 监控项填充的主机资产的ID。 */ private String inventoryLink; /** * */ private String lifetime; /** * SNMPv3认证协议。仅用于SNMPv3监控项。 * * Possible values: * 0 - (default) MD5; * 1 - SHA. */ private String snmpv3Authprotocol; /** * SNMPv3文私密协议。仅用于SNMPv3监控项。 * * Possible values: * 0 - (default) DES; * 1 - AES. */ private String snmpv3Privprotocol; /** *(readonly) State of the item. * * Possible values: * 0 - (default) normal; * 1 - not supported. */ private String state; /** *SNMPv3文本名称。仅用于SNMPv3监控项。 */ private String snmpv3Contextname; /** * */ private String evaltype; /** *JMX agent自定义的连接字符串。 */ private String jmxEndpoint; /** * Master item ID. */ private String masterItemid; /** *HTTP agent监控项字段。监控项数据轮询超时时间。支持用户宏。 */ private String timeout; /** *URL字符串,仅HTTP agent监控项类型需要。支持用户宏 */ private String url; /** *HTTP agent监控项字段。查询参数。带有键值对的数组对象,值可为空。 */ private String queryFelds; /** *HTTP agent字段。HTTP(S)请求报文。仅用于post_type。 */ private String posts; /** * HTTP agent监控项字段。以逗号分隔的HTTP 状态码的范围。也支持作为逗号分隔的用户宏列表。 */ private String statusCodes; /** *HTTP agent 监控项字段。合并数据时跟随重定向。 */ private String followRedirects; /** *HTTP agent字段。存储在post属性的post的数据类型。 */ private String postType; /** *HTTP agent 监控项字段。HTTP(S)代理连接字符串。 */ private String httpProxy; /** *HTTP agent 监控项字段。带有HTTP(S)请求报头的对象,报头名为键名,报头值为值。 */ private String headers; /** * HTTP agent监控项字段。被存储的响应的部分。 */ private String retrieveMode; /** * HTTP agent监控项字段。请求方法的类型。 * * 0 - GET * 1 - (default) POST * 2 - PUT * 3 - HEAD */ private String requestMethod; /** *HTTP agent监控项字段。返回数据应被转换成JSON。 */ private String outputFormat; /** * HTTP agent监控项字段。公共SSL 秘钥的文件路径。 */ private String sslCertFile; /** * HTTP agent监控项字段。私有SLL秘钥的文件路径。 */ private String sslKeyFile; /** * HTTP agent监控项字段。SSL 秘钥的文件密码 */ private String sslKeyPassword; /** * HTTP agent字段。验证主机的合法性。 * * 0 - (default) Do not validate. * 1 - Validate. */ private String verifyPeer; /** * HTTP agent字段。验证URL中的主机名处于通用名称字段或主机证书的主题备用名称字段 * * 0 - (default) Do not validate. * 1 - Validate. */ private String verifyHost; /** *HTTP agent监控项字段。允许和trapper监控项一样的填充值。 * * 0 - (default) Do not allow to accept incoming data. * 1 - Allow to accept incoming data. */ private String allowTraps; /** *监控项最后被更新的时间。 */ private String lastclock; /** * 监控项最后被更新的纳秒。 */ private String lastns; /** * 监控项最新的值。 */ private String lastvalue; /** *监控项的前一个值。 */ private String prevvalue; }
/** * @author : test * @className : ItemValue * @description : 监控项值 * @date : 2024/3/1 15:35 */ @Data public class ItemValue implements Serializable { private String itemid; private String clock; private String value; private String ns; }
9. 测试demo代码
public class ZabbixTest { public static String url = "http://202.100.86.90:12345/api_jsonrpc.php"; public static String user = "yanfaduijie"; public static String password = "h5DHitndTNBAvE"; public static void main(String[] args) { ZabbixApi zabbixApi = new DefaultZabbixApi(url); zabbixApi.init(); boolean login = zabbixApi.login(user, password); if (!login) { throw new RuntimeException("zabbix login failed!"); } String apiVersion = zabbixApi.apiVersion(); System.out.println(apiVersion); JSONArray eventAlarm = zabbixApi.getEventAlarm("1709569900", "1709656300"); List<Dict> list = JSONUtil.toList(eventAlarm, Dict.class); list.forEach( alertList -> { ExApiAlarm exApiAlarm = new ExApiAlarm(); AlarmDto alarmDto = AlarmTypeConversion(alertList); BeanUtils.copyProperties(alarmDto,exApiAlarm); System.out.println(exApiAlarm); } ); List<Host> hosts = zabbixApi.hostListByName("C业务新开虚机-10.50.146.83"); hosts = zabbixApi.hostList(); hosts = zabbixApi.hostListByIp(Arrays.asList("10.50.146.83")); Host host = hosts.get(0); String hostid = host.getHostid(); // 查询主机的监控项 List<Item> items = zabbixApi.hostMonitorItems(hostid); Item item = items.get(0); // 查询第一个监控项的最新值 String itemid = item.getItemid(); Integer valueType = Integer.parseInt(item.getValueType()); ItemValue itemValue = zabbixApi.hostMonitorItemLastValue(itemid, valueType); System.out.println(itemValue); } private static AlarmDto AlarmTypeConversion(Dict dict) { String hostsIp = JSONUtil.toList(dict.getStr("hosts"), Dict.class).get(0).getStr("host"); AlarmDto alarmDto = new AlarmDto(); alarmDto.setSysUpTime(convertTimestampToDateTimeString(dict.getStr("clock"))); alarmDto.setPoolId("0"); alarmDto.setAlarmType(dict.getStr("source")); alarmDto.setAlarmTitle(dict.getStr("name")); alarmDto.setAlarmContent(dict.getStr("name")); alarmDto.setAlarmLevel(extractSeverity(dict.getInt("severity"))); alarmDto.setAlarmTime(dict.getInt("clock")); alarmDto.setObjectId(dict.getStr("objectid")); alarmDto.setSourceIp(hostsIp); alarmDto.setCorrelateAlarmFlag(dict.getInt("value")); alarmDto.setCurrentIp(hostsIp); alarmDto.setAlarmImpact(dict.getStr("name")); alarmDto.setResourceType("主机"); alarmDto.setNotifyType(dict.getInt("value")); return alarmDto; } private static int extractSeverity(Integer inputText) { // 根据严重性值映射到0123 switch (inputText) { case 5: return 0; case 4: return 1; case 3: return 1; case 2: return 2; case 1: return 3; case 0: return 3; default: return -1; // 未知的严重性值 } // 没有找到严重性信息 } public static String convertTimestampToDateTimeString(String timestamp) { long timestampLong = Long.parseLong(timestamp); Instant instant = Instant.ofEpochSecond(timestampLong); LocalDateTime dateTime = LocalDateTime.ofInstant(instant, ZoneId.systemDefault()); // 定义日期时间格式 DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); return dateTime.format(formatter); } }
9. 代码zip压缩包地址
https://files.cnblogs.com/files/blogs/688336/resources.zip?t=1625621275&download=true
该代码参考github上的开源项目,深表感激。。。
标签:Java,String,Zabbix,private,ZABBIX,监控,return,告警,public From: https://www.cnblogs.com/dduo/p/18054443