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

简介:

py -2 -m pip install xxx

172.x.x.x Mac 172.x.x.x mac Template OS Mac OS X ""

我只是添加一个主机,一个模板

api官网
https://www.zabbix.com/documentation/3.2/manual/api/reference/host/create

注意返回值是list还是dict


# !/usr/bin/env python
# coding:utf-8
import json
import urllib2
from urllib2 import URLError
import xlrd
#http://blog.mreald.com/178
import sys
class zabbixtools:
    def __init__(self):
        self.url = "http://zb3.2.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"],
                    "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['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.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 template_get(self, templateName):
        data = json.dumps({
            "jsonrpc": "2.0",
            "method": "template.get",
            "params": {
                "output": "extend",
                "filter": {
                    "host": [
                        templateName,
                    ]
                }
            },
            "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['templateid']
        else:
            return ""

    def host_create(self, hostName, visibleName, hostIp, dnsName, proxyName, hostgroupName, templateName1,
                    templateName2):
        data = json.dumps({
            "jsonrpc": "2.0",
            "method": "host.create",
            "params": {
                "host": hostName,
                "name": visibleName,
                # "proxy_hostid": self.proxy_get(proxyName),
                "interfaces": [
                    {
                        "type": 1,
                        "main": 1,
                        "useip": 1,
                        "ip": hostIp,
                        "dns": dnsName,
                        "port": "10050"
                    }
                ],
                "groups": [
                    {
                        "groupid": self.hostgroup_get(hostgroupName)
                    }
                ],
                "templates": [
                    {
                        "templateid": self.template_get(templateName1)
                    }
                ],
            },
            "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('add_zabbix_hosts.xlsx')
    for row in xrange(workbook.sheets()[0].nrows):
        hostname = workbook.sheets()[0].cell(row, 0).value
        visible = workbook.sheets()[0].cell(row, 1).value
        hostip = workbook.sheets()[0].cell(row, 2).value
        dnsname = workbook.sheets()[0].cell(row, 3).value
        proxy = workbook.sheets()[0].cell(row, 4).value
        hostgroup = workbook.sheets()[0].cell(row, 5).value
        hosttemp = workbook.sheets()[0].cell(row, 6).value
        hosttemp1 = workbook.sheets()[0].cell(row, 7).value
        hostgroup = hostgroup.strip()
        hostnameGet = test.host_get(hostname)
        if hostnameGet.strip() == '':
            test.host_create(hostname, visible, hostip, dnsname, proxy, hostgroup, hosttemp, hosttemp1)
        else:
            print "%s have exist! Cannot recreate !\n" % hostnameGet

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



本文转自 liqius 51CTO博客,原文链接:http://blog.51cto.com/szgb17/2073813,如需转载请自行联系原作者

相关文章
|
7月前
|
API
Poi 中文API文档 「40种操作 Excel文件的姿势」
Poi 中文API文档 「40种操作 Excel文件的姿势」
314 0
|
JSON 监控 前端开发
python对接API二次开发高级实战案例解析:Zabbix API封装类实现获取认证密钥、所有主机组、所有主机、所有监控项和历史数据
python对接API二次开发高级实战案例解析:Zabbix API封装类实现获取认证密钥、所有主机组、所有主机、所有监控项和历史数据
512 0
|
4月前
|
开发框架 .NET API
分享一个 ASP.NET Web Api 上传和读取 Excel的方案
分享一个 ASP.NET Web Api 上传和读取 Excel的方案
129 0
|
7月前
|
监控 网络协议 Unix
centos7 zabbix安装客户端agent -配置监控远程主机 在需要监控的电脑上安装
centos7 zabbix安装客户端agent -配置监控远程主机 在需要监控的电脑上安装
203 0
|
Java API
POI (excel) - API使用与参考
POI (excel) - API使用与参考
91 0
|
监控
通过Zabbix Web界面查看主机的监控方式
通过Zabbix Web界面查看主机的监控方式
273 1
|
监控 网络协议 Unix
zabbix通过agent客户端监控主机
zabbix通过agent客户端监控主机
105 0
|
运维 监控
【运维知识进阶篇】Zabbix5.0稳定版详解10(Zabbix自动注册+Ansible自动部署,实现一条命令监控任意主机)
【运维知识进阶篇】Zabbix5.0稳定版详解10(Zabbix自动注册+Ansible自动部署,实现一条命令监控任意主机)
181 0
|
监控 安全
zabbix测试发邮件报错–连接到Zabbix主机 “localhost“ 失败
zabbix测试发邮件报错–连接到Zabbix主机 “localhost“ 失败
291 0
|
2天前
|
监控 安全 前端开发
使用 Zabbix 监控堆外应用
使用 Zabbix 监控堆外应用
19 9

推荐镜像

更多