python调用zabbix api 实现主机添加等功能

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

import json
import urllib2
from urllib2 import URLError
import sys,argparse


class zabbix_api:

    def __init__(self):
        self.url = 'http://url/zabbix/api_jsonrpc.php'
        self.header = {"Content-Type":"application/json"}
        self.authID = None
        self.hostgroupID = None
        self.templateID = None


    def user_login(self):
        data = json.dumps({
            "jsonrpc": "2.0",
            "method": "user.login",
            "params": {
                         "user": "username",
                         "password": "password"
                       },
            "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 "The request url is error ", e.code
        else:
            response = json.loads(result.read())
            result.close()
            #print response['result']
            self.authID = response['result']
        return self.authID


    def get_host(self):
        data = json.dumps(
            {
              "jsonrpc":"2.0",
              "method":"host.get",
              "params":{
                          "output":["hostid","name"],
                          "filter":{"host":""}
                       },
              "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 Hosts: ", len(response['result'])
            for host in response['result']:
                print "Host ID:",host['hostid'],"Host Name:",host['name']


    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()
            for group in response['result']:
                if len(hostgroupName) == 0:
                    print "groupName: %s ,Groupid: %s " % (group['name'],group['groupid'])
                else:
                    print "groupName: %s ,Groupid: %s " % (group['name'],group['groupid'])
                    self.hostgroupID = group['groupid']
        return group['groupid']


    def template_get(self,templateName=''):
        data = json.dumps({
                           "jsonrpc":"2.0",
                           "method": "template.get",
                           "params": {
                                      "output": "extend",
                                      "filter": {
                                                 "name":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()
            print response['result']
            for template in response['result']:
                if len(templateName) == 0:
                    print "TemplateName: %s , id: %s" % (template['name'],template['templateid'])
                else:
                    self.templateID = response['result'][0]['templateid']
                    print "Template Name: %s " % templateName
        return response['result'][0]['templateid']

    def host_get(self, hostName = ''):
        data = json.dumps({
                "jsonrpc": "2.0",
                "method": "host.get",
                "params": {
                          "output": "extend",
                          "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 "主机数量: \033[31m%s\033[0m" % (len(response['result']))
            for host in response['result']:
                status = {"0":"OK","1":"Disabled"}
                available = {"0":"Unknown","1":"available","2":"Unavailable"}
                if len(hostName) == 0:
                    print "HostID : %s\t HostName : %s\t Status :\033[32m%s\033[0m \t Available :\033[31m%s\033[0m"%(host['hostid'],host['name'],status[host['status']],available[host['available']])
                else:
                    print "HostID : %s\t HostName : %s\t Status :\033[32m%s\033[0m \t Available :\033[31m%s\033[0m"%(host['hostid'],host['name'],status[host['status']],available[host['available']])
                return 1


    def host_create(self, hostdns, hostgroupName, templateName):
        if self.host_get(hostdns):
            print " 该主机已经添加! "
            return

        group_list = []
        template_list = []
        for i in hostgroupName.split(','):
            var = {}
            var['groupid'] = self.hostgroup_get(i)
            group_list.append(var)
        for i in templateName.split(','):
            var ={}
            var['templateid'] = self.template_get(i)
            print self.template_get(i)
            template_list.append(var)

        print group_list
        print template_list
        data = json.dumps({
                           "jsonrpc":"2.0",
                           "method":"host.create",
                           "params":{
                                     "host": hostdns,
                                     "interfaces": [
                                     {
                                         "type": 1,
                                         "main": 1,
                                         "useip": 0,
                                         "ip": "",
                                         "dns": hostdns,
                                         "port": "10050"
                                      }
                                     ],
                                    "groups": group_list,
                                    "templates": template_list,
                                     },
                           "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()
            if response.has_key('error'):
                print "添加主机失败"
                print response
            else:
                print "添加主机成功"
                #print "添加主机 : \033[42m%s\031[0m \tid :\033[31m%s\033[0m" % (hostdns, response['result']['hostids'])


    def requestJason(self,url,values):
        data = json.dumps(values)
        req = urllib2.Request(url, data, {'Content-Type': 'application/json-rpc'})
        response = urllib2.urlopen(req, data)
        data_get = response.read()
        output = json.loads(data_get)
        print output
        try:
            message = output['result']
        except:
            message = output['error']['data']
            quit()
        print json.dumps(message)
        return output


    def getGraphs(self,host_list,name_list, url, columns, graphtype=0, dynamic=0):
        if graphtype == 0:
            selecttype = ['graphid']
            select = 'selectGraphs'
        if graphtype == 1:
            selecttype = ['itemid', 'value_type']
            select = 'selectItems'
        values = ({'jsonrpc': '2.0',
                "method": "graph.get",
                "params": {
                     select: [selecttype,"name"],
                    "output": ["graphid","name"],
                    "hostids": host_list,
                    "filter":{'name':name_list},
                    "sortfield":"name",
                },
                "auth": self.user_login(),
                "id": '3'
            })
        print values
        output = self.requestJason(url,values)
        bb = sorted(output['result'],key = lambda x:x['hosts'][0]['hostid'])
        output['result'] = bb
        graphs = []
        if (graphtype == 0):
            for i in output['result']:
                print i
                graphs.append(i['graphid'])
        if (graphtype == 1):
            for i in output['result']:
                if int(i['value_type']) in (0, 3):
                    graphs.append(i['itemid'])
        graph_list = []
        x = 0
        y = 0
        print graphs
        for graph in graphs:
            print "x is " + str(x)
            print "y is " + str(y)
            graph_list.append({
                "resourcetype": graphtype,
                "resourceid": graph,
                "width": "500",
                "height": "100",
                "x": str(x),
                "y": str(y),
                "colspan": "0",
                "rowspan": "0",
                "elements": "0",
                "valign": "0",
                "halign": "0",
                "style": "0",
                "url": "",
                "dynamic": str(dynamic)
            })
            x += 1
            print type(x)
            print type(columns)
            if x == int(columns):
                x = 0
                y += 1
        print graph_list
        return graph_list


    def screenCreate(self, url, screen_name, graphids, columns):
        columns = int(columns)
        if len(graphids) % columns == 0:
            vsize = len(graphids) / columns
        else:
            vsize = (len(graphids) / columns) + 1
        values = {"jsonrpc": "2.0",
                  "method": "screen.create",
                  "params": [{
                      "name": screen_name,
                      "hsize": columns,
                      "vsize": vsize,
                      "screenitems": []
                  }],
                  "auth": self.user_login(),
                  "id": 1
                  }
        for i in graphids:
            values['params'][0]['screenitems'].append(i)
        output = self.requestJason(url,values)


if __name__ == '__main__':
    za = zabbix_api()
    #za.hostgroup_get("Proxy QT HK")
    #za.template_get("Template OS Linux")
    #za.host_get('***.***.com')
    #za.getGraphs("***.***.com","Template OS Linux: CPU load","")
    #za.host_create("***.***.com","Proxy QT HK","Template OS Linux")   #普通香港代理
    #za.host_create("***.***.com","Proxy QT Other","Template OS Linux") #台湾日本
    #za.host_create("***.***.com","DDOS","Template OS Linux")                #高防
    #za.host_create("***.***.com","Proxy QT Other","Template OS Linux")      #其他
    #za.host_create("***.***.com","Proxy Game","Template OS Linux")      #GAME
    #za.host_create("***.***.com","Proxy QT NewHK","Template OS Linux")      #香港新机房


你可能感兴趣的:(python,api,zabbix)