1. 程式人生 > WINDOWS開發 >zabbix通過api 批量自動新增主機

zabbix通過api 批量自動新增主機

自動新增主機

官網api: zabbix_api

import requests
import json
import os

# user config here
ip = ‘10.0.0.1‘
user = "user"
password = "pass."


# user config end

class ZabbixApi:
    def __init__(self,ip,user,password):
        self.url = ‘https://‘ + ip + ‘/api_jsonrpc.php‘
        self.headers = {"Content-Type": "application/json",}
        self.user = user
        self.password = password
        self.auth = self.__login()

    def __login(self):
        ‘‘‘
        zabbix登陸獲取auth
        :return: auth  #  樣例bdc64373690ab9660982e0bafe1967dd
        ‘‘‘
        data = json.dumps({
            "jsonrpc": "2.0","method": "user.login","params": {
                "user": self.user,"password": self.password
            },"id": 10,# "auth": ‘none‘
        })
        try:
            response = requests.post(url=self.url,headers=self.headers,data=data,timeout=2)
            # {"jsonrpc":"2.0","result":"bdc64373690ab9660982e0bafe1967dd","id":10}
            auth = response.json().get(‘result‘,‘‘)
            return auth
        except Exception as e:
            print("\033[0;31;0m Login error check: IP,USER,PASSWORD\033[0m")
            raise Exception

    def host_get(self,hostname=‘‘):
        ‘‘‘
        獲取主機。不輸入hostname 則獲取所有
        :param hostName: zabbix主機名不允許重複。(IP允許重複)。#host_get(hostname=‘gateway1‘)
        :return: {‘jsonrpc‘: ‘2.0‘,‘result‘: [],‘id‘: 21}
        :return: {‘jsonrpc‘: ‘2.0‘,‘result‘: [{‘hostid‘: ‘10277‘,...,‘host‘: ‘gateway‘,...}],‘id‘: 21}
        ‘‘‘
        if hostname == ‘‘:
            # print("no hostname and find all host")
            data = json.dumps({
                "jsonrpc": "2.0","method": "host.get","params": {
                    "output": [
                        "hostid","host"
                    ],"selectInterfaces": [
                        "interfaceid","ip"
                    ]
                },"id": 20,"auth": self.auth
            })
        else:
            data = json.dumps({
                "jsonrpc": "2.0","params": {"output": "extend","filter": {"host": hostname},},"id": 21,"auth": self.auth
            })
        try:
            response = requests.get(url=self.url,timeout=2)
            # hosts_count=len(response.json().get(‘result‘,‘‘))
            # print(‘l‘,hosts)
            return response.json()  # len(ret.get(‘result‘))為1時獲取到,否則未獲取到。
        except Exception as e:
            print("\033[0;31;0m HOST GET ERROR\033[0m")
            raise Exception

    def hostgroup_get(self,hostGroupName=‘‘):
        ‘‘‘
        獲取主機組
        :param hostGroupName:
        :return: {‘jsonrpc‘: ‘2.0‘,‘result‘: [{‘groupid‘: ‘15‘,‘name‘: ‘linux group 1‘,‘internal‘: ‘0‘,‘flags‘: ‘0‘}],‘id‘: 1}
        ‘‘‘
        data = json.dumps({
            "jsonrpc": "2.0","method": "hostgroup.get","params": {
                "output": "extend","filter": {
                    "name": hostGroupName
                }
            },"auth": self.auth,"id": 1,})
        try:
            response = requests.get(url=self.url,hosts)
            return response.json()  # len(ret.get(‘result‘))為1時獲取到,否則未獲取到。

        except Exception as e:
            print("\033[0;31;0m HOSTGROUP GET ERROR\033[0m")
            raise Exception

    def hostgroup_create(self,hostGroupName=‘‘):
        if len(self.hostgroup_get(hostGroupName).get(‘result‘)) == 1:
            print("無需建立,hostgroup存在")
            return 100
        data = json.dumps({
            "jsonrpc": "2.0","method": "hostgroup.create","params": {
                "name": hostGroupName
            },"id": 1
        })
        try:
            response = requests.get(url=self.url,hosts)
            return response.json()  # len(ret.get(‘result‘))為1時獲取到,否則未獲取到。

        except Exception as e:
            print("\033[0;31;0m HOSTGROUP CREATE ERROR\033[0m")
            raise Exception

    def template_get(self,templateName=‘‘):
        data = json.dumps({
            "jsonrpc": "2.0","method": "template.get","filter": {
                    "name": templateName
                }
            },"id": 50,hosts)
            return response.json()  # len(ret.get(‘result‘))為1時獲取到,否則未獲取到。

        except Exception as e:
            print("\033[0;31;0m Template GET ERROR\033[0m")
            raise Exception

    def host_create(self,hostname,hostip,hostGroupName,templateName):
        # 判斷主機名是否重複
        find_hostname = self.host_get(hostname)
        if len(find_hostname.get(‘result‘)):
            print("###recheck### hostname[%s] exists and return" % hostname)
            return 1

        # 判斷template是否存才,不存在退出。 否則初始化備用
        template_list = []
        for t in templateName.split(‘,‘):
            find_template = self.template_get(t)
            if not len(find_template.get(‘result‘)):
                # template不存在退出 # 一般因為輸錯關係
                print("###recheck### template[%s] not find and return " % t)
                return 1

            tid = self.template_get(t).get(‘result‘)[0][‘templateid‘]
            template_list.append({‘templateid‘: tid})

        # 判斷hostgroup是否存在。 不存在則建立。 並
        hostgroup_list = []
        for g in hostGroupName.split(‘,‘):
            find_hostgroupname = self.hostgroup_get(g)
            if not len(find_hostgroupname.get(‘result‘)):
                # hostgroupname 不存在,建立
                self.hostgroup_create(g)
            gid = self.hostgroup_get(g).get(‘result‘)[0][‘groupid‘]
            hostgroup_list.append({‘groupid‘: gid})


        data = json.dumps({
            "jsonrpc": "2.0","method": "host.create","params": {
                "host": hostname,"interfaces": [
                    {
                        "type": 1,"main": 1,"useip": 1,"ip": hostip,"dns": "","port": "10050",}
                ],"groups": hostgroup_list,"templates": template_list,"proxy_hostid": 13404,# 我這使用了代理,不需要代理 去掉函式就可以
            },"id": 1
        })

        try:
            response = requests.get(url=self.url,hosts)
            print("執行返回資訊: 新增HOST[%s,%s]完成" % (hostname,hostip))
            return response.json()  # len(ret.get(‘result‘))為1時獲取到,否則未獲取到。

        except Exception as e:
            print("\033[0;31;0m HOST CREATE ERROR\033[0m")
            raise Exception


if __name__ == ‘__main__‘:
    try:
        zabbix = ZabbixApi(ip,password)
        print("...login success...")

        # 批量新增主機,從文字add_host.txt
        BASE_DIR = os.path.dirname(os.path.abspath(__file__))
        ADD_LIST = os.path.join(BASE_DIR,‘add_host.txt‘)
        with open(ADD_LIST,‘r‘,encoding=‘utf-8‘) as f:
            for line in f:
                if len(line.strip()):  # 跳過空行
                    serverinfo = line.strip().split(‘#‘)
                    # 根據自己需要進行修改
                    zabbix.host_create(serverinfo[0],serverinfo[1],serverinfo[2],serverinfo[3])

    except Exception as e:
        print(e)


更改為txt格式
主機 ip 群組 代理
host1 #10.1.1.1# #test# #proxy1
host2 #10.1.1.1# #test2# #proxy2

host#ip#gropup#proxy

轉:https://www.jianshu.com/p/e087cace8ddf