SpringBootでZabbixAPIを使ってみる

 Zabbixの作業を自動化したいという事で、ZabbixAPIを使ってみました。対象のZabbixは3.2とちょっと古めのようですが、API自体はあまりバージョンは気にしなくてよさそうでした。ドキュメントが充実しているので助かります。

認証後、2件のホストを指定してホスト情報を取ってくるテストを書いてみました。

	@Test
	public void testZabbixAPI() throws Exception {
		String zabbixUser = "zabbixuser";
		String zabbixPass = "****";
		String zabbixEndpoint = "http://zabbixserver/zabbix/api_jsonrpc.php";

		//認証
		JSONObject json = new JSONObject();
		json.put("user", zabbixUser);
		json.put("password", zabbixPass);
		json.put("userData", "false");
		
		String token = null;
		ResponseEntity<String> response = Request("user.login", json, zabbixEndpoint, token);
		
	    JsonNode root = new ObjectMapper().readTree(response.getBody());
	    
	    token = root.get("result").get("sessionid").asText();

		//ホスト情報取得
		JSONObject target = new JSONObject();
	    String[] chkTarget = {"server01","server02"};
		JSONArray targetArray = new JSONArray(chkTarget);
	    
    	JSONObject param = new JSONObject();
		param.put("output", new JSONArray(Arrays.asList("hostid","host","name")));
		target.put("host", targetArray);
		param.put("filter", target);

		response = Request("host.get", param, zabbixEndpoint, token);
		ObjectMapper mapper = new ObjectMapper();
		ArrayNode arrayHost = (ArrayNode) mapper.readTree(response.getBody()).path("result");
		
	    System.out.println("hosts: " + arrayHost);
    }
	
	private ResponseEntity<String> Request(String method, JSONObject param, String endPoint, String token) throws Exception {
		JSONObject json = new JSONObject();

		json.put("jsonrpc", "2.0");
        json.put("method", method);
        json.put("params", param);
        json.put("id", 1);
		if(token != null){
            json.put("auth", token);
        }
        HttpMethod httpMethod = HttpMethod.POST;
        
	    HttpEntity <String> entity ;
		HttpHeaders headers = new HttpHeaders();
	    headers.add("Content-Type", "application/json-rpc");
	    headers.add("Accept-Language", "ja");
	    
	    if(param == null){
	    	entity = new HttpEntity <String>(headers);
	    }
	    else{
	    	entity = new HttpEntity <String>(json.toString(), headers);
	    }
	    RestTemplate restTemplate = new RestTemplate();
	    restTemplate.getMessageConverters()
        .add(0, new StringHttpMessageConverter(Charset.forName("UTF-8")));
	    
	    ResponseEntity<String> response = restTemplate.exchange(endPoint, httpMethod, entity, String.class);
	    
		return response;
	}

で、こんな感じで戻ってきます。

hosts: [{“hostid”:”10387″,”host”:”server01″,”name”:”server01_DB”},{“hostid”:”10388″,”host”:”server02″,”name”:”server02_DB”}]

問題無く使えそうなので、要件を整理してから実装してみます。