利用zabbix api添加、删除、禁用主机

  1. python环境配置
    yum -y install python-pip
    安装argparse模块
    pip install -i https://pypi.douban.com/simple/ argparse
  2. 脚本修改
    请修改脚本中zabbix登录地址以及zabbix管理员帐户及密码

    #!/usr/bin/env python
    #-*- coding: utf-8 -*-
    
    import json
    import sys
    import urllib2
    import argparse
    
    from urllib2 import URLError
    
    reload(sys)
    sys.setdefaultencoding(‘utf-8‘)
    
    class zabbix_api:
        def __init__(self):
            self.url = ‘http://zab.test.com/api_jsonrpc.php‘
            self.header = {"Content-Type":"application/json"}
    
        def user_login(self):
            data = json.dumps({
                               "jsonrpc": "2.0",
                               "method": "user.login",
                               "params": {
                                          "user": "admin",
                                          "password": "zabbix"
                                          },
                               "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 "\033[041m 认证失败,请检查URL !\033[0m",e.code
            except KeyError as e:
                print "\033[041m 认证失败,请检查用户名密码 !\033[0m",e
            else:
                response = json.loads(result.read())
                result.close()
                #print response[‘result‘]
                self.authID = response[‘result‘]
                return self.authID
    
        def hostid_get_hostname(self, hostId=‘‘):
            data = json.dumps({
                "jsonrpc": "2.0",
                "method": "host.get",
                "params": {
                    "output": "extend",
                    "filter": {"hostid": hostId}
                },
                "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())
                #print response
                result.close()
    
                if not len(response[‘result‘]):
                    print "hostId is not exist"
                    return False
    
                #print "主机数量: \33[31m%s\33[0m" % (len(response[‘result‘]))
                host_dict=dict()
                for host in response[‘result‘]:
                    status = {"0": "OK", "1": "Disabled"}
                    available = {"0": "Unknown", "1": "available", "2": "Unavailable"}
                    #if len(hostId) == 0:
                    #    print "HostID : %s\t HostName : %s\t Status :\33[32m%s\33[0m \t Available :\33[31m%s\33[0m" % (
                    #        host[‘hostid‘], host[‘name‘], status[host[‘status‘]], available[host[‘available‘]])
                    #else:
                    #    print "HostID : %s\t HostName : %s\t Status :\33[32m%s\33[0m \t Available :\33[31m%s\33[0m" % (
                    #        host[‘hostid‘], host[‘name‘], status[host[‘status‘]], available[host[‘available‘]])
                    host_dict[‘name‘]=host[‘name‘]
                    host_dict[‘status‘]=status[host[‘status‘]]
                    host_dict[‘available‘]=available[host[‘available‘]]
                    return host_dict
    
        def hostid_get_hostip(self, hostId=‘‘):
            data = json.dumps({
                "jsonrpc": "2.0",
                "method": "hostinterface.get",
                "params": {
                    "output": "extend",
                    "filter": {"hostid": hostId}
                },
                "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())
                # print response
                result.close()
    
                if not len(response[‘result‘]):
                    print "\033[041m hostid \033[0m is not exist"
                    return False
    
                #print "主机数量: \33[31m%s\33[0m" % (len(response[‘result‘]))
                for hostip in response[‘result‘]:
                    #print hostip
                    #if len(hostip) == 0:
                    #    print "HostID : %s\t HostIp : %s \t Port : %s " % (hostip[‘hostid‘], hostip[‘ip‘], hostip[‘port‘])
                    #else:
                    #    print "HostID : %s\t HostIp :\33[32m%s\33[0m \t Port :\33[31m%s\33[0m" % (
                    #        hostip[‘hostid‘], hostip[‘ip‘], hostip[‘port‘])
                    return hostip[‘ip‘]
    
        def host_get(self,hostName=‘‘):
            data=json.dumps({
                    "jsonrpc": "2.0",
                    "method": "host.get",
                    "params": {
                              "output": "extend",
                              #"filter":{"host":""}
                              "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())
                #print reqponse
                result.close()
    
                if not len(response[‘result‘]):
                    print "\033[041m %s \033[0m is not exist" % hostName
                    return False
    
                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"}
                    #print host
                    if len(hostName)==0:
                        print "HostID : %s\t HostName : %s\t HostIp : %s\t Status :%s \t Available :%s"%(host[‘hostid‘],host[‘name‘],self.hostid_get_hostip(hostId=host[‘hostid‘]),status[host[‘status‘]],available[host[‘available‘]])
                    else:
                        print "HostID : %s\t HostName : %s\t HostIp : %s\t Status :\033[32m%s\033[0m \t Available :\033[31m%s\033[0m"%(host[‘hostid‘],host[‘name‘],self.hostid_get_hostip(hostId=host[‘hostid‘]),status[host[‘status‘]],available[host[‘available‘]])
                        return host[‘hostid‘]
    
        def hostip_get(self, hostIp=‘‘):
            data = json.dumps({
                "jsonrpc": "2.0",
                "method": "hostinterface.get",
                "params": {
                    "output": "extend",
                    "filter": {"ip": hostIp}
                },
                "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())
                # print response
                result.close()
    
                if not len(response[‘result‘]):
                    print "\033[041m hostip \033[0m is not exist"
                    return False
    
                print "主机数量: \33[31m%s\33[0m" % (len(response[‘result‘]))
                for hostip in response[‘result‘]:
                    host = self.hostid_get_hostname(hostip[‘hostid‘])
                    if len(hostip) == 0:
                        print "HostID : %s\t HostName : %s\t HostIp : %s\t Status :\33[32m%s\33[0m \t Available :\33[31m%s\33[0m"%(hostip[‘hostid‘],host[‘name‘],hostip[‘ip‘],host[‘status‘],host[‘available‘])
                    else:
                        print "HostID : %s\t HostName : %s\t HostIp : %s\t Status :\33[32m%s\33[0m \t Available :\33[31m%s\33[0m"%(hostip[‘hostid‘],host[‘name‘],hostip[‘ip‘],host[‘status‘],host[‘available‘])
                        return hostip[‘hostid‘]
    
        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:
                # result.read()
                response = json.loads(result.read())
                result.close()
                #print response()
                if not len(response[‘result‘]):
                    print "\033[041m %s \033[0m is not exist" % hostgroupName
                    return False
    
                for group in response[‘result‘]:
                    if  len(hostgroupName)==0:
                        print "hostgroup:  \033[31m%s\033[0m \tgroupid : %s" %(group[‘name‘],group[‘groupid‘])
                    else:
                        print "hostgroup:  \033[31m%s\033[0m\tgroupid : %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
                if not len(response[‘result‘]):
                    print "\033[041m %s \033[0m is not exist" % templateName
                    return False
    
                for template in response[‘result‘]:
                    if len(templateName)==0:
                        print "template : %s \t id : %s" % (template[‘name‘], template[‘templateid‘])
                    else:
                        self.templateID = response[‘result‘][0][‘templateid‘]
                        print "Template Name :%s"%templateName
                        return response[‘result‘][0][‘templateid‘]
    
        def hostgroup_create(self,hostgroupName):
            if self.hostgroup_get(hostgroupName):
                print "hostgroup  \033[42m%s\033[0m is exist !" % hostgroupName
                sys.exit(1)
    
            data = json.dumps({
                              "jsonrpc": "2.0",
                              "method": "hostgroup.create",
                              "params": {
                              "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()
                print "添加主机组:%s  hostgroupID : %s"%(hostgroupName,self.hostgroup_get(hostgroupName))
    
        def host_create(self, hostIp, hostgroupName, templateName, hostName):
            if self.host_get(hostName) or self.hostip_get(hostIp):
                print "该主机已经添加!"
                sys.exit(1)
    
            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)
                template_list.append(var)
    
            data = json.dumps({
                               "jsonrpc":"2.0",
                               "method":"host.create",
                               "params":{
                                         "host": hostName,
                                         "interfaces": [
                                         {
                                         "type": 1,
                                         "main": 1,
                                         "useip": 1,
                                         "ip": hostIp,
                                         "dns": "",
                                         "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)
                response = json.loads(result.read())
                result.close()
                print "add host : %s id :%s" % (hostIp, hostName)
            except URLError as e:
                print "Error as ", e
            except KeyError as e:
                print "\033[041m 主机添加有误,请检查模板正确性或主机是否添加重复 !\033[0m",e
                print response
    
        def host_disable(self,hostip):
            data=json.dumps({
                    "jsonrpc": "2.0",
                    "method": "host.update",
                    "params": {
                    "hostid": self.host_get(hostip),
                    "status": 1
                    },
                    "auth": self.user_login(),
                    "id": 1
                    })
            request = urllib2.Request(self.url,data)
            #opener = urllib2.build_opener(urllib2.HTTPBasicAuthHandler(TerminalPassword()))
            for key in self.header:
                    request.add_header(key, self.header[key])
            try:
                result = urllib2.urlopen(request)
                #result = opener.open(request)
            except URLError as e:
                print "Error as ", e
            else:
                response = json.loads(result.read())
                result.close()
                print ‘------------主机现在状态------------‘
                print self.host_get(hostip)
    
        def host_enable(self,hostip):
            data=json.dumps({
                "jsonrpc": "2.0",
                "method": "host.update",
                "params": {
                "hostid": self.host_get(hostip),
                "status": 0
                },
                "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)
                #result = opener.open(request)
            except URLError as e:
                print "Error as ", e
            else:
                response = json.loads(result.read())
                result.close()
                print ‘------------主机现在状态------------‘
                print self.host_get(hostip)
    
        def host_delete(self,hostNames):
            hostid_list=[]
            for hostName in hostNames.split(‘,‘):
                hostid = self.host_get(hostName=hostName)
                if not hostid:
                    print "主机 \033[041m %s\033[0m  删除失败 !" % hostName
                    sys.exit()
                hostid_list.append(hostid)
    
            data=json.dumps({
                    "jsonrpc": "2.0",
                    "method": "host.delete",
                    "params": hostid_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)
                result.close()
                print "主机 \033[041m %s\033[0m  已经删除 !" % hostName
            except Exception,e:
                print  e
    
    if __name__ == "__main__":
        zabbix=zabbix_api()
        parser=argparse.ArgumentParser(description=‘zabbix api ‘,usage=‘%(prog)s [options]‘)
        parser.add_argument(‘-H‘,‘--host‘,nargs=‘?‘,dest=‘listhost‘,default=‘host‘,help=‘查询主机‘)
        parser.add_argument(‘-G‘,‘--group‘,nargs=‘?‘,dest=‘listgroup‘,default=‘group‘,help=‘查询主机组‘)
        parser.add_argument(‘-T‘,‘--template‘,nargs=‘?‘,dest=‘listtemp‘,default=‘template‘,help=‘查询模板信息‘)
        parser.add_argument(‘-A‘,‘--add-group‘,nargs=1,dest=‘addgroup‘,help=‘添加主机组‘)
        parser.add_argument(‘-C‘,‘--add-host‘,dest=‘addhost‘,nargs=4,metavar=(‘192.168.2.1‘, ‘groupname‘, ‘Template01,Template02‘, ‘hostName‘),help=‘添加主机,多个主机组或模板用逗号‘)
        parser.add_argument(‘-d‘,‘--disable‘,dest=‘disablehost‘,nargs=‘+‘,metavar=(‘sh-aa-01‘),help=‘禁用主机,填主机名‘)
        parser.add_argument(‘-e‘,‘--enable‘,dest=‘enablehost‘,nargs=‘+‘,metavar=(‘sh-aa-01‘),help=‘开启主机,填主机名‘)
        parser.add_argument(‘-D‘,‘--delete‘,dest=‘deletehost‘,nargs=‘+‘,metavar=(‘sh-aa-01‘),help=‘删除主机,填主机名‘)
        parser.add_argument(‘-v‘,‘--version‘, action=‘version‘, version=‘%(prog)s 1.0‘)
    
        if len(sys.argv) == 1:
            print parser.print_help()
            #print zabbix.host_get(hostName=‘bbb‘)
            #print zabbix.hostip_get(hostIp=‘127.0.0.1‘)
            #print zabbix.hostid_get_hostname(hostId=‘10108‘)
            #print zabbix.hostid_get_hostid(hostId=‘10105‘)
            #print zabbix.hostgroup_get(hostgroupName=‘Linux servers‘)
            #print zabbix.hostgroup_get(hostgroupName=‘aaa‘)
            #print zabbix.host_delete(‘hz-aaa-02‘)
        else:
            args = parser.parse_args()
            if args.listhost != ‘host‘:
                if args.listhost:
                    zabbix.host_get(args.listhost)
                else:
                    zabbix.host_get()
            if args.listgroup != ‘group‘:
                if args.listgroup:
                    zabbix.hostgroup_get(args.listgroup)
                else:
                    zabbix.hostgroup_get()
            if args.listtemp != ‘template‘:
                if args.listtemp:
                    zabbix.template_get(args.listtemp)
                else:
                    zabbix.template_get()
            if args.addgroup:
                zabbix.hostgroup_create(args.addgroup[0])
            if args.addhost:
                zabbix.host_create(args.addhost[0], args.addhost[1], args.addhost[2], args.addhost[3])
            if args.disablehost:
                zabbix.host_disable(args.disablehost)
            if args.enablehost:
                zabbix.host_enable(args.enablehost)
            if args.deletehost:
                zabbix.host_delete(args.deletehost[0])

    zbx_tools.py

    (原文地址:https://www.jianshu.com/p/e087cace8ddf)

  3. 使用方法
    帮助说明
    python zbx_tools.py
    查询主机
    python zbx_tools.py -H
    查询主机组
    python zbx_tools.py -G
    查询模板信息
    python zbx_tools.py -T | grep Linux
    添加主机组
    python zbx_tools.py -A ADDGROUP
    添加主机
    python zbx_tools.py -C  10.10.40.20 "Linux servers" "Template OS Linux" "HostName_Test"
    python zbx_tools.py -C 10.10.40.20 "Linux servers","Discovered hosts" "Template OS Linux","Template App HTTP Service" "HostName_Test"
    禁用主机
    python zbx_tools.py -d "HostName_Test"
    开启主机
    python zbx_tools.py -e "HostName_Test"
    删除主机
    python zbx_tools.py -D "HostName_Test"

原文地址:https://www.cnblogs.com/Mrhuangrui/p/8206194.html

时间: 2024-10-27 18:56:58

利用zabbix api添加、删除、禁用主机的相关文章

python利用zabbix API添加监控

首先说一下坑的地方就是python2和python3的模块改变问题,当然精通python的可以略过.这个在网上百度一下吧,第二个是导入xlsx文件的时候需要xlrd模块,而这个模块最好跟着我下面的方法走,那个python2 就可以用我下边的脚本了. 1.安装xlrd读取Excel文件 1.1. 下载setuptools-38.2.4.zip,上传至zabbix服务器解压安装,下载地址:https://pypi.python.org/packages/69/56/f0f52281b5175e3d9

通过Zabbix API 添加host

脚本内容: #!/usr/bin/python #-*- coding:utf8 -*- import json,sys,argparse from zabbix_api import ZabbixAPI server = "http://172.16.206.128/zabbix" username = "Admin" password = "zabbix" zapi = ZabbixAPI(server=server, path="

利用Zabbix API创建主机宏

#!/usr/bin/python #coding:utf-8 from zabbix_api import ZabbixAPI import json server="http://172.16.206.130/zabbix" username="Admin" password="zabbix" zapi = ZabbixAPI(server=server,path="",log_level=0) zapi.login(us

利用zabbix API进行管理

zabbix 现在之所以那么流行,个人感觉跟zabbix 强大的API有一个很大的关系,利用API可以帮我们完成很多事情: 1.获取相关组,主机信息. 2.比如有人喜欢获取历史数据重新出图. 3.添加删除主机,绑定删除模板. 4.添加删除维护周期 这里我使用pipy提供的zabbix_client模块来进行,这样就不用我们自己去写登录函数,只要在模块开始指定用户名密码即可: 1.安装zabbix_client: pip install zabbxi_client 2.API管理脚本,替换成自己用

基于zabbix API添加监控主机

由于zabbix监控的主机虽为同一个业务,但是由于其跨机房并且网络为为16位,两个机房导致zabbix的自动添加扫描的主机数量就差不多有12w多个,严重影响其效率和性能. 使用zabbix API的基本步骤如下: 连接http://x.x.x.x/api_jsonrpc.php,(在zabbix网页文件的目录下为api_jsonrpc.php),提供用户名和密码,并标识HTTP头部"Content-Type":"application/json",HTTP方法为po

利用zabbix api 带入 组ID 和 监控项目键值 获取所有主机的值

def  chaxun(groupid,items_value):  是自己写的,带入组ID 和 监控项目键值,返回 主机和值的结果. 做了判断,如果这个主机没有想要的监控项目,就去除掉. #!/usr/bin/env python #coding=utf-8 import urllib.request import json import re url = 'http://XXXXXXXXXXXXXXXX/api_jsonrpc.php' username = 'Admin' password

利用Zabbix API 创建主机

#!/usr/bin/env python2.7 # coding=utf-8 from zabbix_api import ZabbixAPI import urllib2 import sys ###get visible_name inet_ip=sys.argv[1] url = 'http://10.47.102.185/api/ecs/?ip={0}'.format(inet_ip) response = urllib2.urlopen(url) result = response.

利用Zabbix API 获取各个分组下的服务器列表以及详细信息

现在越来越多的公司选择使用开源软件Zabbix来做服务器业务监控,其高逼格的用户管理是个亮点,所以可以通过调用它的接口将权限管理应用到很多地方,比如说堡垒机权限.以下是用python简单写了个小脚本,通过定义分组名便可以得到分组下的服务器信息. #coding=utf-8 __author__ = 'Perling' from urllib import urlencode import urllib2 import json def post(post_data):     api_url =

zabbix批量添加主机监控-zabbix api调用

使用python调用zabbix api #!/usr/bin/env python # Version = 3.6.1 # __auth__ = 'warren' import json from urllib import request, parse ZABBIX_URL = 'http://192.168.22.22/zabbix' ZABBIX_USERNAME = "Admin" ZABBIX_PASSWORD = "123456" #以列表形式定义要添