Call ZABBIX-API to add a large number of monitoring hosts to liberate the hands of operation and maintenance monitoring

Posted by mydownfall on Tue, 15 Oct 2019 16:32:23 +0200

In the work, the number of servers in the company may be too large. When hundreds of monitored hosts need to be added at a time, the traditional simple web side of zabbix has a heavy workload of adding monitored hosts, which is also prone to errors.

At this time, script automatic operation is particularly important. Today, we will talk about the operation of using ZABBIX-API interface to increase the monitored host in batches.

1. Write ZABBIX-API-custom Library

The custom library does not need to be changed, and there is no difference. Please pay attention to the python version, which is indicated in the code. Please choose to use your own version.
#!/usr/bin/python
# encoding: utf-8
#filename: zabbix_base_api.py
#author: LINFAN
#writetime:20190725

import json
import urllib.request #Python 3 uses
#import urllib2   #python2 use

class zabbix_base_api(object):

    def __init__(self,url = "http://192.168.73.9/api_jsonrpc.php" ,header = {"Content-Type": "application/json"}):
        self.url = url
        self.header = header
    # post
    def post_request(self,url, data, header):
       # request = urllib2.Request(url, data, header)    #python2 use
       # result = urllib2.urlopen(request)
#
        request = urllib.request.Request(url, data, header)   #Use of Python 3
        result = urllib.request.urlopen(request)
    #    ccc = result.read()
    #   print (ccc)
    #    response = json.loads(ccc)
        response = json.loads(result.read())
        result.close()
        return response

    def json_data(self,method,params,authid):
        data = json.dumps(
        {
            "jsonrpc": "2.0",
            "method": method,
            "params": params,
            "auth": authid,
             "id": 1
        })
        request_info = self.post_request(self.url, data.encode('utf-8'), self.header)

        return request_info
    # Authentication information
    def authid(self,user,password): #Determine the information of auth in json
        data = json.dumps(
        {
            "jsonrpc": "2.0",
            "method": "user.login",
            "params": {
                "user": user,
                "password": password
            },
            "id": 1
        })
        authid = self.post_request(self.url, data.encode('utf-8'), self.header)
        try:
            return authid['result']
        except KeyError:
            print ('Wrong user name or password')
            exit()

    def text_process(self,file):
        import re
        find = re.compile(r"^#")
        text_info = []
        # f =  open(file,"r",encoding='UTF-8')
        f = open(file, "r")
        text = f.readlines()
        f.close()
        for i in text:
            if find.search(i.rstrip("\n")) == None:
                text_info.append(i.rstrip("\n"))
        return text_info

    # Cancellation certification
    def login_out(self,authid):
        data = json.dumps(
        {
            "jsonrpc": "2.0",
            "method": "user.logout",
            "params": [],
            "id": 1,
            "auth": authid
        })
        a = self.post_request(self.url, data.encode('utf-8'), self.header)
        return 'Authentication information has been cancelled'

2. Write script to add monitored host

#!/usr/bin/python
# encoding: utf-8

import zabbix_base_api  # Call ZABBIX API custom library 
import time 

z_api_con = zabbix_base_api.zabbix_base_api(url='http://Server? IP / API? Jsonrpc. PHP ')? Fill in the server IP address of your ZABBIX

def getHostid(method,ip,authid):
    data = {
        "output": ["hostid", "host"],
        "filter": {
            "ip": ip
        },
        "selectInterfaces": ["ip"],
        "selectParentTemplates": ["name"]

    }
    responses = z_api_con.json_data(method, data, authid)
    return responses
#Please be there. web Point the mouse at the name of agent, group and template, and the corresponding ID#
def hostCreate(method,ip,authid):
    data = {
        "host": ip,
        "proxy_hostid": 13323,                    #Agent unique identification code
        "interfaces": [
            {
                "type": 1,
                "main": 1,
                "useip": 1,
                "ip": ip,
                "dns": "",
                "port": "10050"                       #port
            }
        ],
        "groups": [
            {
                "groupid": 222                               #Unique identification of the group
            }
        ],

        "templates": [
            {
                "templateid": 14041                                #Unique identification of the template
            }
        ]
    }

    responses = z_api_con.json_data(method, data, authid)
    return responses

def proxyGet(method,hostid,authid):
    data = {
        "output": "extend",
        "selectInterface": "extend"
    }
    responses = z_api_con.json_data(method, data, authid)
    return responses

def proxyUpdate(method,hostid,authid):
    data = {
        "proxyid": 10255,              #No change required here#                        
        "hosts": [
            hostid
        ]
    }
    responses = z_api_con.json_data(method, data, authid)
    return responses

def main_all(authid):
    file = open("a.txt", "r") #Open the ip file
    lists = file.readlines()
    print (lists)
    add_file = open("c.txt","a+")
    iplist = []
    for list in lists:
        ip = list.strip("\n")

#Determine whether the host exists, write the hostid and IP to the file ((c.txt)), create if not, and write the IP to the file (c.txt)
        hostget = getHostid("host.get",ip,authid)["result"]
        print(hostget)
        if hostget:
            hostid = hostget[0]["hostid"]
            host = hostget[0]["host"]
            add_file.writelines(hostid+"\t"+host+"\n")
        else:
            hostcreate = hostCreate("host.create",ip,authid)
            print(hostcreate)
            add_file.writelines(ip+"\n")

    add_file.close()
    file.close()

if __name__ == "__main__":
    starttime = time.time()
    print ("Process is running...")
    authid = z_api_con.authid('zabbix Accounts', 'zabbix Password')
    # authid = z_api_con.authid('admin','zabbix')
    main_all(authid)
    z_api_con.login_out(authid)
    endtime = time.time()
    print (endtime-starttime)

Here I use the tester to tunnel locally and execute scripts directly locally using pycha tools. I try it myself, free my hands! Ha-ha

Topics: Linux Zabbix JSON Python encoding