设为首页 收藏本站
查看: 819|回复: 0

[经验分享] 基于zabbix api根据hostname关联多个template

[复制链接]

尚未签到

发表于 2019-1-24 11:23:49 | 显示全部楼层 |阅读模式
基于zabbix api根据hostname添加多个template

          之前写了一个关联模版的api但是考虑到每个添加一个template是有点复杂,而且最近有那么一个需求,所以改了一下方法,使得可以根据hostname添加多个template。
  话不多说直接上脚本和效果:
  

(env1) ➜  ~ cat zabbix_add_template.py
#!/usr/bin/python
#-*- coding:utf-8 -*-
#__author__ == 'chenmingle'
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://www.zabbix.com:8088/zabbix/api_jsonrpc.php'
        self.header = {"Content-Type":"application/json"}
    def user_login(self):
        data = json.dumps({
                           "jsonrpc": "2.0",
                           "method": "user.login",
                           "params": {
                                      "user": "zabbix",
                                      "password": "zabbixpasswd"
                                      },
                           "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_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())
            result.close()
            if not len(response['result']):
                print "\033[041m hostid \033[0m is not exist"
                return False
            for hostip in response['result']:
                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 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 template_massadd(self, templateName, hostName):
        template_list=[]
        for i in templateName.split(','):
            template_list = self.template_get(i)
            print template_list
            host_id = self.host_get(hostName)
            print host_id
            data = json.dumps({
                "jsonrpc": "2.0",
                "method": "template.massadd",
                "params": {
                    "templates": [
                        {
                            "templateid": template_list,
                        }
                    ],
                    "hosts": [
                        {
                            "hostid": host_id
                        }
                    ]
                },
                               "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 %s to hosts: %s" % (templateName, hostName)
            except URLError as e:
                print "Error as ", e
            except KeyError as e:
                print "\033[041m 主机添加有误,请检查模板正确性或主机是否添加重复 !\033[0m",e
                print response
if __name__ == "__main__":
    zabbix=zabbix_api()
    parser=argparse.ArgumentParser(description='zabbix api ',usage='%(prog)s [options]')
    parser.add_argument('-t','--template_messadd',dest='template_massadd',nargs=2,metavar=('Template01,Template02', 'hostName'),help='添>加主机,多个主机组或模板使用逗号')
    args = parser.parse_args()
    zabbix.template_massadd(args.template_massadd[0], args.template_massadd[1])  执行脚本:

(env1) ➜  ~ python zabbix_add_template.py -t 'Template App HTTP Service','Template ICMP Ping' testServer_***_WEB
Template Name :Template App HTTP Service
10094
主机数量: 1
HostID : 10477 HostName : testServer_***_WEB HostIp : 106.75.***.*** Status :OK  Available :available
10477
add Template App HTTP Service,Template ICMP Ping to hosts: testServer_***_WEB
Template Name :Template ICMP Ping
10104
主机数量: 1
HostID : 10477 HostName : testServer_***_WEB HostIp : 106.75.***.*** Status :OK  Available :available
10477
add Template App HTTP Service,Template ICMP Ping to hosts: testServer_***_WEB  查看zabbix web上是否已经关联模版:






运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.yunweiku.com/thread-666976-1-1.html 上篇帖子: 更改zabbix数据库的密码 下篇帖子: centos7.2用rpm包安装zabbix
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

扫码加入运维网微信交流群X

扫码加入运维网微信交流群

扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

扫描微信二维码查看详情

客服E-mail:kefu@iyunv.com 客服QQ:1061981298


QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



合作伙伴: 青云cloud

快速回复 返回顶部 返回列表