最新消息:

Zabbix API python版本

api admin 4185浏览 0评论
#!/usr/bin/python
# -*- coding: utf-8 -*-

import urllib2
import sys
import json


class zabbixtools:
 
    def __init__(self):
        self.url = "http://192.168.1.100/zabbix/api_jsonrpc.php"
        self.header = {"Content-Type": "application/json"}
        self.authID = self.user_login()

    def user_login(self):
        data = json.dumps(
            {
                "jsonrpc": "2.0",
                "method": "user.login",
                "params": {
                    "user": "admin",
                    "password": "admin"
                    },
                "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()
            authID = response['result']
            return authID

    def get_data(self,data,hostip=""):
        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 fulfaild the request"
                print "error code:",e.code
            return 0
        else:
            response = json.loads(result.read())
            result.close()
            return response


    def host_get(self,hostip):
        # 生成json格式数据
        print self.authID
        data = json.dumps(     
            {
                "jsonrpc": "2.0",
                "method": "host.get",
                "params": {
                    "output":["hostid","name","status","host", "ip", "host"],
                    "filter": {"host": [hostip]}
                    },
                "auth": self.authID,
                "id": 1
            })
        print self.get_data(data)
        res = self.get_data(data)['result']
        if (res != 0) and (len(res) != 0):
            host = res[0]
            # print host
            if host['status']  == 1:
                print "\x1b[1;32mHost_IP: %s Host_Name: %s down\x1b[0m" % (host['host'],host['name'])
                return host['hostid']
            else:
                print host
                print "\x1b[1;32mHost_ip: %s Host_Name: %s up\x1b[0m" % (host['host'],host['name'])
                return host['hostid']
        else:
            print "host_get error please check define host_get()"
            return 0

    def hostgroup_get(self):
        data = json.dumps(
            {
                "jsonrpc":"2.0",
                "method":"hostgroup.get",
                "params":{
                    "output":"extend"
                    },
                "auth":self.authID,
                "id":1
            })
        res = self.get_data(data)
        if 'result' in res.keys():
            res = res['result']
            # print res
            if (res != 0) and (len(res) != 0):
                for host in res:
                    print "\x1b[1;32mHost_id: %s  Hostgroup_name: %s\x1b[0m" % (host['groupid'],host['name'])
        else:
            print "Host_Group info  Gets the Error"

    def template_get(self):
        data = json.dumps(
            {
                "jsonrpc":"2.0",
                "method":"template.get",
                "params":{
                    "output":"extend"
                    },
                "auth":self.authID,
                "id":1
            })

        res = self.get_data(data)
        if 'result' in res.keys():
            res = res['result']
            if (res != 0) and (len(res) != 0):
                for host in res:
                    print "\x1b[1;32mTemplate_id: %s  Template_name: %s\x1b[0m" % (host['templateid'],host['name'])
        else:
            print "Templateid gets the error"

    def host_delete(self):
        hostip = raw_input("please input your delete hostip:")
        hostid = self.host_get(hostip)
        if hostid == 0:
            print "\x1b[1;31mhost_get error please check it"
            sys.exit()
        # print hostid
        data = json.dumps(
            {
                "jsonrpc":"2.0",
                "method":"host.delete",
                "params":[{"hostid":hostid}],
                "auth":self.authID,
                "id":1
            })

        res = self.get_data(data)['result']
        if 'hostids' in res.keys():
            print "\x1b[1;32m%s删除成功!!!\x1b[0m" % hostip
        else:
            print "\x1b[1;31m%s删除失败!!!\x1b[0m" % hostip

    def host_create(self):
        hostip = raw_input("please input hostip:")
        groupid = raw_input("please input groupid:")
        templateid = raw_input("please input templateid:")
        g_list = []
        t_list = []
        for i in groupid.split(','):
            var = {}
            var['groupid'] = i
            g_list.append(var)
        for i in templateid.split(','):
            var = {}
            var['templateid'] = i
            t_list.append(var)
        if hostip and groupid and templateid:
            data = json.dumps(
                {
                    "jsonrpc":"2.0",
                    "method":"host.create",
                    "params":{
                        "host":hostip,
                        "interfaces":[
                            {
                                "type":1,
                                "main":1,
                                "useip":1,
                                "ip":hostip,
                                "dns":"",
                                "port":"10050",
                            }
                        ],
                        "groups":g_list,
                        "templates":t_list
                    },
                        "auth":self.authID,
                        "id":1
                })
            res = self.get_data(data,hostip)
            if 'result' in res:
                res = res['result']
                if 'hostids' in res.keys():
                    print "\x1b[1;32m%s \t\t主机添加成功\x1b[0m" % hostip
            else:
                print "\x1b[1;31m%s \t\t主机添加失败\x1b[0m" % hostip
        else:
            print "您输入的参数有误."

if __name__ == '__main__':
    a = zabbixtools()
    #print a.hostgroup_get()
    #a.hostgroup_get()
    #a.template_get()
    #a.host_create()
    #a.host_delete()
    a.host_get('yq70')

转载请注明:爱开源 » Zabbix API python版本

您必须 登录 才能发表评论!