Zabbix 调用API 批量添加主机到主机组中 (读取Excel)

简介:

注意的地方
1.host_get方法
return host['groups'][0]['groupid']
return host['hostid']
2."selectGroups": "extend"
3.[{'groupid': u'2'}, {'groupid': u'16'}]

逻辑
host_get
host_get_group
hostgroup_get 从名字到groupid
host_update

ip mac(所属新组)

# !/usr/bin/env python
# coding:utf-8
import json
import urllib2
from urllib2 import URLError
import xlrd
import sys
import copy
import os
class zabbixtools:
    def __init__(self):
        self.url = "http://zb3.com/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": "user",
                        "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 "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 fulfill the request.'
                print 'Error code: ', e.code
            return 0
        else:
            response = json.loads(result.read())
            result.close()
            return response

    def host_get(self,hostip):
        # hostip = raw_input("\033[1;35;40m%s\033[0m" % 'Enter Your Check Host:Host_ip :')
        data = json.dumps(
            {
                "jsonrpc": "2.0",
                "method": "host.get",
                "params": {
                    "output": ["hostid", "name", "status", "host","groupids"],
                    "selectGroups": "extend",
                    "filter": {"host": [hostip]}
                },
                "auth": self.authID,
                "id": 1
            })
        res = self.get_data(data)['result']
        if (res != 0) and (len(res) != 0):
            # for host in res:
            print type(res)
            host = res[0]
            # return host['groups'][0]['groupid']
            # return host['hostid']
            return host
        else:
            return ""

    def host_get_group(self,hostip):
        group_list = []
        # hostip = raw_input("\033[1;35;40m%s\033[0m" % 'Enter Your Check Host:Host_ip :')
        data = json.dumps(
            {
                "jsonrpc": "2.0",
                "method": "host.get",
                "params": {
                    "output": ["hostid", "name", "status", "host","groupids"],
                    "selectGroups": "extend",
                    "filter": {"host": [hostip]}
                },
                "auth": self.authID,
                "id": 1
            })
        res = self.get_data(data)['result']
        if (res != 0) and (len(res) != 0):
            print type(res)
            groups = res[0]['groups']
            for group in groups:
                var = {}
                var['groupid'] = group['groupid']
                group_list.append(var)
            # return host['groups'][0]['groupid']
            return group_list
        else:
            return ""

    def hostgroup_get(self,hostgroupName):
        data = json.dumps(
            {
                "jsonrpc": "2.0",
                "method": "hostgroup.get",
                "params": {
                    "output": "extend",
                    "filter": {"name": [hostgroupName]}
                },
                "auth": self.authID,
                "id": 1
            })
        res = self.get_data(data)['result']
        if (res != 0) and (len(res) != 0):
            # for host in res:
            print type(res)
            host = res[0]
            return host['groupid']
        else:
            return ""

    def host_update(self,hostIp,hostgroupName):
        print hostIp,hostgroupName
        data = json.dumps({
            "jsonrpc": "2.0",
            "method": "host.update",
            "params": {
                # "hostid": '10202',
                "hostid": self.host_get(hostIp)['hostid'],
                "groups": hostgroupName,
                "status": 0,
            },
            "auth": self.authID,
            "id": 1
        })
        res = self.get_data(data)['result']

        if (res != 0) and (len(res) != 0):
            # for host in res:
            print type(res)
            # print res['hostids'][0]
            return res['hostids'][0]
        else:
            return ""

if __name__ == "__main__":
    test = zabbixtools()
    workbook = xlrd.open_workbook('addhost_to_hostgroup.xlsx')
    for row in xrange(workbook.sheets()[0].nrows):
        hostIp = workbook.sheets()[0].cell(row, 0).value
        hostgroupName = workbook.sheets()[0].cell(row, 1).value
        hostgroup_old = test.host_get_group(hostIp)
        #获取目前主机的所属组
        hostgroup_id = test.hostgroup_get(hostgroupName)
        hostgroup_new = [{'groupid': hostgroup_id}]
        #判断新增的组是否存在目前主机的所属组
        for groupid in  hostgroup_new:
            if groupid not in hostgroup_old:
                hostgroup_old_format = copy.deepcopy(hostgroup_old)
                hostgroup_old_format.append(groupid)
                print hostgroup_old_format
                test.host_update(hostIp,hostgroup_old_format)


本文转自 liqius 51CTO博客,原文链接:http://blog.51cto.com/szgb17/2073955,如需转载请自行联系原作者
相关文章
|
API
Poi 中文API文档 「40种操作 Excel文件的姿势」
Poi 中文API文档 「40种操作 Excel文件的姿势」
627 0
|
JSON 监控 前端开发
python对接API二次开发高级实战案例解析:Zabbix API封装类实现获取认证密钥、所有主机组、所有主机、所有监控项和历史数据
python对接API二次开发高级实战案例解析:Zabbix API封装类实现获取认证密钥、所有主机组、所有主机、所有监控项和历史数据
743 0
|
11月前
|
JSON 监控 API
使用Zabbix API
使用Zabbix API
655 67
|
开发框架 .NET API
分享一个 ASP.NET Web Api 上传和读取 Excel的方案
分享一个 ASP.NET Web Api 上传和读取 Excel的方案
389 0
|
Java API
POI (excel) - API使用与参考
POI (excel) - API使用与参考
201 0
|
JSON 监控 前端开发
Zabbix监控系统PHP-API开发测试实录
Zabbix监控系统PHP-API开发测试实录
415 0
|
监控 API 数据库
|
1月前
|
缓存 监控 前端开发
顺企网 API 开发实战:搜索 / 详情接口从 0 到 1 落地(附 Elasticsearch 优化 + 错误速查)
企业API开发常陷参数、缓存、错误处理三大坑?本指南拆解顺企网双接口全流程,涵盖搜索优化、签名验证、限流应对,附可复用代码与错误速查表,助你2小时高效搞定开发,提升响应速度与稳定性。
|
1月前
|
JSON 算法 API
Python采集淘宝商品评论API接口及JSON数据返回全程指南
Python采集淘宝商品评论API接口及JSON数据返回全程指南
|
2月前
|
数据可视化 测试技术 API
从接口性能到稳定性:这些API调试工具,让你的开发过程事半功倍
在软件开发中,接口调试与测试对接口性能、稳定性、准确性及团队协作至关重要。随着开发节奏加快,传统方式已难满足需求,专业API工具成为首选。本文介绍了Apifox、Postman、YApi、SoapUI、JMeter、Swagger等主流工具,对比其功能与适用场景,并推荐Apifox作为集成度高、支持中文、可视化强的一体化解决方案,助力提升API开发与测试效率。

推荐镜像

更多