Java连接Zabbix

下面例子我们通过调用Zabbix的API获取到我们Zabbix所产生的告警信息。

Zabbix Api官方手册:https://www.zabbix.com/documentation/3.0/en/manual/api

要想获取到Zabbix上的其他信息,可以参考我们的Zabbix Api进行配置!


 导入相关maven

<dependency>
  <groupId>junit</groupId>
  <artifactId>junit</artifactId>
  <version>4.11</version>
  <scope>test</scope>
</dependency>
<dependency>
  <groupId>org.mortbay.jetty</groupId>
  <artifactId>servlet-api</artifactId>
  <version>2.5-20081211</version>
</dependency>
<dependency>
  <groupId>com.alibaba</groupId>
  <artifactId>fastjson</artifactId>
  <version>1.2.76</version>
</dependency>

实现类

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.zabbix.dao.ZabbixDao;
import com.zabbix.dao.ZabbixDaoImpl;
import com.zabbix.utils.EditTool;

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.*;

/**
 * @author 
 * @since 
 */
public class ZabbixUtil {

    private static String       URL      = "http://192.168.111.131/zabbix/api_jsonrpc.php";   //Zabbix访问地址

    private static String       AUTH     = null;   

    private static final String USERNAME = "Admin";   //登录Zabbix的用户名

    private static final String PASSWORD = "zabbix";  //密码


    /**
     * 向Zabbix发送Post请求,并返回json格式字符串
     *
     * @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);
            //中文用户名需设置UTF-8,out.write(param.getBytes("UTF-8"));
            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("id", 0);
        map.put("auth", null);


        String response = sendPost(map);
        JSONObject json = JSON.parseObject(response);
        AUTH = json.getString("result");
    }

    private static String getAuth() {
        if (AUTH == null) {
            setAuth();
        }
        return AUTH;
    }


    /**
     * 通过IP获得主机hostid
     *
     * @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;
        }
    }


    /**
     * 通过IP获取主机名称
     *
     * @return 返回hostname @
     */
    private static String getHostname(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 hostname = json.getString("host");
            return hostname;
        } else {
            return null;
        }
    }
    /**
     * 通过主机IP获取告警信息
     *
     * @return 返回mailMap @
     */
    private static List actionById(String ip) {
        List list=new ArrayList();
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("output", "extend");
        params.put("hostids", getHostIdByIp(ip));
        params.put("selectFunctions","extend");

        Map<String, Object> map = new HashMap<String, Object>();
        map.put("jsonrpc", "2.0");
        map.put("method", "trigger.get");
        map.put("params", params);
        map.put("auth", getAuth());
        map.put("id", 1);

        JSONObject json = null;
        String response = sendPost(map);
        JSONArray result = JSON.parseObject(response).getJSONArray("result");
        if (result.size() > 0) {
            for (int i = 0; i < result.size(); i++) {
                json = result.getJSONObject(i);
                Map warnMap=new HashMap();
                warnMap.put("description",json.getString("description"));
                warnMap.put("value",json.getString("value"));
                warnMap.put("priority",json.getString("priority"));
                list.add(warnMap);
            }
            return list;
        } else {
            return null;
        }
    }


    @Override
    public void run(){
        setAuth();
        String ip = "192.168.111.130";  //要获取信息的主机IP地址

        //获取数据库接口
        ZabbixDao dBtest = new ZabbixDaoImpl();
        //获取主机名称
        String hostName = getHostname(ip);
        //通过主机id获取告警信息
        List list = actionById(ip);
        //获取告警具体某字段信息
        if(list != null && !list.isEmpty()){
            for(int i=0;i<list.size();i++){
                Map warnMap=(Map)list.get(i);
                String warn_content= String.valueOf(warnMap.get("description"));
                String warn_type= String.valueOf(warnMap.get("priority"));
                String warn_status= String.valueOf(warnMap.get("value"));
            }
        }
    }
}

 

posted @ 2022-02-22 15:41  RFAA  阅读(623)  评论(0编辑  收藏  举报