zabbix通过API批量添加主机

参考链接:https://blog.csdn.net/weixin_34107955/article/details/89821524

脚本内容

#coding:utf-8
  
import json
import urllib2
from urllib2 import URLError
import sys
import xlrd
  
class ZabbixTools: 
    def __init__(self): 
        self.url = 'http://zabbix-dashboard.gc1.pt.gomedc.com/zabbix/api_jsonrpc.php'
        #self.url = 'http://10.128.52.177/zabbix/api_jsonrpc.php'
        self.header = {"Content-Type":"application/json"}
    
	# 登陆验证
    def user_login(self): 
        data = json.dumps({ 
                           "jsonrpc": "2.0", 
                           "method": "user.login", 
                           "params": { 
                                      "user": "Admin", 
                                      "password": "mq6N2lHnqBphkjqCYTsW" 
                                      }, 
                           "id": 0 
                           }) 
          
        request = urllib2.Request(self.url, data) 
        for key in self.header: 
            request.add_header(key, self.header[key]) 
      
        try: 
            result = urllib2.urlopen(request) 
        except URLError as e: 
            print "Auth Failed, please Check your name and password:", e.code 
        else: 
            response = json.loads(result.read()) 
            result.close() 
            self.authID = response['result'] 
            return self.authID


    def host_get(self,hostName): 
        data = json.dumps({ 
                           "jsonrpc":"2.0", 
                           "method":"host.get", 
                           "params":{ 
                                     "output":["hostid","name"], 
                                     "filter":{"host":hostName} 
                                     }, 
                           "auth":self.user_login(), 
                           "id":1, 
                           }) 
          
        request = urllib2.Request(self.url, data) 
        for key in self.header: 
            request.add_header(key, self.header[key]) 
              
      
        try: 
            result = urllib2.urlopen(request) 
        except URLError as e: 
            if hasattr(e, 'reason'): 
                print 'We failed to reach a server.' 
                print 'Reason: ', e.reason 
            elif hasattr(e, 'code'): 
                print 'The server could not fulfill the request.' 
                print 'Error code: ', e.code 
        else: 
            response = json.loads(result.read()) 
            result.close() 
            print "Number Of %s: " % hostName, len(response['result']) 
            lens=len(response['result']) 
            if lens > 0:
                return response['result'][0]['name']
            else:
                return ""


    def hostgroup_get(self, hostgroupName):
        data = json.dumps({ 
                           "jsonrpc":"2.0", 
                           "method":"hostgroup.get", 
                           "params":{ 
                                     "output": "extend", 
                                     "filter": { 
                                                "name": [ 
                                                         hostgroupName, 
                                                         ] 
                                                } 
                                     }, 
                           "auth":self.user_login(), 
                           "id":1, 
                           })

        request = urllib2.Request(self.url, data)
        for key in self.header:
            request.add_header(key, self.header[key])

        try:
            result = urllib2.urlopen(request)
        except URLError as e:
            print "Error as ", e 
        else:
            response = json.loads(result.read())
            result.close()

            lens=len(response['result'])
            if lens > 0:
                self.hostgroupID = response['result'][0]['groupid']
                return response['result'][0]['groupid']
            else:
                print "no GroupGet result"
                return ""

    def template_get(self, templateName): 
        data = json.dumps({ 
                           "jsonrpc":"2.0", 
                           "method": "template.get", 
                           "params": { 
                                      "output": "extend", 
                                      "filter": { 
                                                 "host": [ 
                                                          templateName, 
                                                          ] 
                                                 } 
                                      }, 
                           "auth":self.user_login(), 
                           "id":1, 
                           }) 
          
        request = urllib2.Request(self.url, data) 
        for key in self.header: 
            request.add_header(key, self.header[key]) 
               
        try: 
            result = urllib2.urlopen(request) 
        except URLError as e: 
            print "Error as ", e 
        else: 
            response = json.loads(result.read()) 
            result.close() 
            self.templateID = response['result'][0]['templateid'] 
            return response['result'][0]['templateid']


# 创建host
    #def host_create(self, hostName,visibleName,hostIp,dnsName,proxyName, hostgroupName, templateName1, templateName2): 
    def host_create(self, hostName,hostIp,proxyName,hostgroupName,templateName1,templateName2,templateName3,templateName4,templateName5,templateName6): 
        data = json.dumps({ 
                           "jsonrpc":"2.0", 
                           "method":"host.create", 
                           "params":{ 
                                     "host": hostName, 
                                     "proxy_hostid": self.proxy_get(proxyName),
                                     "interfaces": [ 
                                                        { 
                                                            "type": 1, 
                                                            "main": 1, 
                                                            "useip": 1, 
                                                            "ip": hostIp, 
                                                            "dns": "", 
                                                            "port": "11050" 
                                                        } 
                                                    ], 
                                    "groups": [ 
                                                    { 
                                                        "groupid": self.hostgroup_get(hostgroupName) 
                                                    } 
                                               ], 
                                     "tags": [
                                                    {
                                                        "tag": "主机名称",
                                                        "value": ""
                                                    },
                                                    {
                                                        "tag": "IP",
                                                        "value": hostIp
                                                    },
                                                    {
                                                        "tag": "类型",
                                                        "value": ""
                                                    },
                                                    {
                                                        "tag": "配置",
                                                        "value": ""
                                                    },
                                                    {
                                                        "tag": "机房",
                                                        "value": ""
                                                    },
                                                    {
                                                        "tag": "环境",
                                                        "value": "prod"
                                                    },
                                                    {
                                                        "tag": "应用名称",
                                                        "value": ""
                                                    },
                                                    {
                                                        "tag": "项目名称",
                                                        "value": ""
                                                    },
                                                    {
                                                        "tag": "项目负责人",
                                                        "value": ""
                                                    },
                                                    {
                                                        "tag": "所属组织",
                                                        "value": ""
                                                    }
                                               ],
                                    "templates": [ 
                                                    { 
                                                        "templateid": self.template_get(templateName1)
                                                          
                                                    },
                                                    { 
                                                         
                                                        "templateid": self.template_get(templateName2) 
                                                    }, 
                                                    {

                                                        "templateid": self.template_get(templateName3)
                                                    },
                                                    {

                                                        "templateid": self.template_get(templateName4)
                                                    },
                                                    {

                                                        "templateid": self.template_get(templateName5)
                                                    },
                                                    {

                                                        "templateid": self.template_get(templateName6)
                                                    }
                                                  ], 
                                     }, 
                           "auth": self.user_login(), 
                           "id":1                   
        }) 
        request = urllib2.Request(self.url, data) 
        for key in self.header: 
            request.add_header(key, self.header[key]) 
               
        try: 
            result = urllib2.urlopen(request) 
        except URLError as e: 
            print "Error as ", e 
        else: 
            response = json.loads(result.read()) 
            result.close() 
            print "host : %s is created!   id is  %s\n" % (hostIp, response['result']['hostids'][0]) 
            self.hostid = response['result']['hostids'] 
            return response['result']['hostids'] 
    
	# zabbix_proxy获取函数     
    def proxy_get(self, ProxyName):
        data = json.dumps({
                           "jsonrpc":"2.0",
                           "method": "proxy.get",
                           "params": {
                                      "output": "extend",
                                      "selectInterface": "extend",
                                      "filter": {
                                          "host": [ ProxyName, ]
                                      }
                                      },
                           "auth":self.user_login(),
                           "id":1,
                           })
 
        request = urllib2.Request(self.url, data)
        for key in self.header:
            request.add_header(key, self.header[key])
 
        try:
            result = urllib2.urlopen(request)
        except URLError as e:
            print "Error as ", e
        else:
            response = json.loads(result.read())
            result.close()
            self.templateID = response['result'][0]['proxyid']
            return response['result'][0]['proxyid']


          
if __name__ == "__main__": 
          
    test = ZabbixTools() 
 
    workbook = xlrd.open_workbook('test.xlsx')
    for row in xrange(workbook.sheets()[0].nrows):
        hostname=workbook.sheets()[0].cell(row,0).value
        hostIp=workbook.sheets()[0].cell(row,1).value
        proxyName=workbook.sheets()[0].cell(row,2).value
        hostgroup=workbook.sheets()[0].cell(row,3).value
        hosttemp1=workbook.sheets()[0].cell(row,4).value
        hosttemp2=workbook.sheets()[0].cell(row,5).value
        hosttemp3=workbook.sheets()[0].cell(row,6).value
        hosttemp4=workbook.sheets()[0].cell(row,7).value
        hosttemp5=workbook.sheets()[0].cell(row,8).value
        hosttemp6=workbook.sheets()[0].cell(row,9).value

        hostgroup=hostgroup.strip()
        hosttemp1=hosttemp1.strip()
        hosttemp2=hosttemp2.strip()
        hosttemp3=hosttemp3.strip()
        hosttemp4=hosttemp4.strip()
        hosttemp5=hosttemp5.strip()
        hosttemp6=hosttemp6.strip()

        hostnameGet=test.host_get(hostname)
        print hostnameGet
        #print hostname + ',' + hostIp + ',' + proxyName + ',' + hostgroup + ',' +  hosttemp1 + ',' +  hosttemp2 + ',' + hosttemp3 + ',' + hosttemp4 + ',' + hosttemp5 + ',' + hosttemp6

        if hostnameGet.strip() == '':
            test.host_create(hostname,hostIp,proxyName,hostgroup,hosttemp1,hosttemp2,hosttemp3,hosttemp4,hosttemp5,hosttemp6)
        else:
            print "%s have exist! Cannot recreate !\n" % hostnameGet

 

 

posted @ 2022-03-31 14:22  摩天居士-谢烟客  阅读(167)  评论(0编辑  收藏  举报