zabbix_addhost.py 12.1 KB
#!/usr/bin/python
# encoding:utf-8

#######################################################
#   author: liuh    2018-10-28
#   version: v1.0
#   python version: 2
#######################################################

import json
import urllib2
from urllib2 import URLError
import sys
import xlrd
import getopt

class ZabbixTools:
    def __init__(self, url, user, passwd):
        self.url = url
        self.header = {"Content-Type":"application/json"}
        self.user = user
        self.passwd = passwd

	# 登陆验证
    def user_login(self):
        data = json.dumps({
                           "jsonrpc": "2.0",
                           "method": "user.login",
                           "params": {
                                      "user": self.user,
                                      "password": self.passwd
                                      },
                           "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,visibleName,hostIp, hostgroupName, proxyName, templateName1, templateName2):
        root_dict =  {
                           "jsonrpc":"2.0",
                           "method":"host.create",
                           "params":{
                                     "host": hostName,
                                     "name": visibleName,
                                     "interfaces": [
                                                        {
                                                            "type": 1,
                                                            "main": 1,
                                                            "useip": 1,
                                                            "ip": hostIp,
                                                            "dns": "",
                                                            "port": "10050"
                                                        }
                                                    ],
                                    "groups": [
                                                    {
                                                        "groupid": self.hostgroup_get(hostgroupName)
                                                    }
                                               ],
                                    # "templates": [
                                    #                 {
                                    #                     "templateid": self.template_get(templateName1)

                                    #                 },
                                    #                 {

                                    #                     "templateid": self.template_get(templateName2)
                                    #                 }
                                    #               ],
                                     },
                           "auth": self.user_login(),
                           "id":1
        }
        if(proxyName != ""):
          root_dict["params"]["proxy_hostid"] = self.proxy_get(proxyName)

        templates = []
        if(templateName1 != ""):
          templates.append({"templateid": self.template_get(templateName1)})
        if(templateName2 != ""):
          templates.append({"templateid": self.template_get(templateName2)})
        if len(templates) > 0:
          root_dict["params"]["templates"] = templates

        data = json.dumps(root_dict)
        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']

def usage():
    print("""
    useage: zabbix_addhost.py [options]

        [+]--baseurl=[any] | zabbix web url           | default: http://192.168.9.133:9210
        [+]--ipstart=[any] | ip range start           | default: 192.168.66.2
        [+]--ipend=[any] | ip range end               | default: 192.168.66.41
        [+]--user=[any] | zabbix web login user       | default: Admin
        [+]--passwd=[any] | zabbix web login password | default: zabbix
        [+]--hostgroup=[any] | host group name        | default: tx1
        [+]--proxyname=[any] | porxy name             | default: ""
        [+]--template1=[any] | template name 1        | default: "starnet_tx1_slave_tp"
        [+]--template2=[any] | template name 2        | default: "Template OS Linux"
            
    """)
# 程序的入口
if __name__ == "__main__":
    try:
        options,args = getopt.getopt(sys.argv[1:],"",["help","baseurl=","ipstart=", "ipend=", "user=",\
          "passwd=", "hostgroup=", "proxyname=", "template1=", "template2="])
    except getopt.GetoptError:
        print("error: invalid args")
        usage()
        sys.exit(-1)


    baseurl = "http://192.168.9.133:9210"
    ipstart = "192.168.66.2"
    ipend = "192.168.66.2"
    user = "Admin"
    passwd = "zabbix"
    hostgroup = "tx1"
    proxyname = ""
    template1 = "starnet_tx1_slave_tp"
    template2 = "Template OS Linux"


    for name,value in options:
        if name in ("--help"):
          usage()
        if name in ("--baseurl"):
          baseurl = value
        if name in ("--ipstart"):
          ipstart = value
        if name in ("--ipend"):
          ipend = value
        if name in ("--user"):
          user = value
        if name in ("--passwd"):
          passwd = value
        if name in ("--hostgroup"):
          hostgroup = value
        if name in ("--proxyname"):
          proxyname = value
        if name in ("--template1"):
          template1 = value
        if name in ("--template2"):
          template2 = value

    print("baseurl={}\n ipstart={}\n ipend={}\n user={}\n passwd={}\n hostgroup={}\n proxyname={}\n template1={}\n template2={}\n".format(\
      baseurl, ipstart, ipend, user, passwd, hostgroup, proxyname, template1, template2))
    url=baseurl+"/api_jsonrpc.php"
    # # 实例化ZabbixTools对象
    test = ZabbixTools(url, user, passwd)

    sstrs = ipstart.split(".")
    estrs = ipend.split(".")
    ipbase = "{}.{}.{}".format(sstrs[0], sstrs[1], sstrs[2])
    intstart = int(sstrs[3])
    intend = int(estrs[3])

    # ipbase = "192.168.66"
    for i in range(intstart,intend+1):
        hostip = "{}.{}".format(ipbase,i)
        print(hostip)
        hostname = proxyname+'_'+hostip
        test.host_create( hostname,hostname,hostip, hostgroup, proxyname, template1, template2)