• zabbix api添加主机


    #!/usr/bin/env  python
    #-*- coding:utf-8 -*-
    import sys
    import json
    import urllib2
    from optparse import OptionParser
    class ZabbixApi():
        def __init__(self):
            self.url="https://zabbix_address/api_jsonrpc.php"
            self.header={"Content-Type":"application/json"}
        def Token(self):
            data=json.dumps({
                "jsonrpc": "2.0",
                "method": "user.login",
                "params": {
                    "user": "xxxxx",
                    "password": "xxxxx"
                     },
                "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())
                 return response['result']
            except urllib2.URLError as e:
                print "33[031m Api 认证失败,请检查URL!33[0m"
            except KeyError as e:
                print "33[031m Api 认证失败,请检查用户名密码!33[0m"
        def HostGroupList(self):
            data=json.dumps({
                "jsonrpc": "2.0",
                "method": "hostgroup.get",
                "params": {
                    "output": "extend",
                            },
                "auth": self.Token(),
                "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())
                 print "33[31m主机组数量: %s33[0m"%len(response['result'])
                 for hostgroup in response['result']:
                     print "33[1;36;40mGroup ID: %s 33[0m "%hostgroup['groupid'],"	33[1;36;40mGroup Name: %s 33[0m"%hostgroup['name']
            except Exception as e:
                 print e
        def HostInGroups(self):
            #groupid=raw_input("33[1;38m请输入你想要查看的GroupID33[0m:")
            data=json.dumps({
                "jsonrpc": "2.0",
                "method": "host.get",
                "params": {
                           "output":["hostid","name","status"],
                           "groupids": sys.argv[2],
                          },
                "auth": self.Token(),
                "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())
                print "33[31m主机数量: %s33[0m"%len(response['result'])
                for host in  response['result']:
                    if host['status']=='0':
                        host['status']="已启用"
                    else:
                        host['status']="已停用"
                    print "33[1;36;40mHost ID: %s 33[0m "%host['hostid'],"	33[1;36;40mHost Name: %s 33[0m"%host['name'],"	33[1;30;40m%s33[0m"%host['status']
            except Exception  as e:
                print e
        def UpdateHostStatus(self):
            hostid=raw_input("33[1;38m请输入想要更新状态的HostID33[0m:")
            hostStatus=raw_input("33[1;38m请输入想要更新主机状态(0:启用,1:停用)33[0m:")
            data=json.dumps({
                "jsonrpc": "2.0",
                "method": "host.update",
                "params": {
                      "hostid": hostid,
                      "status": hostStatus,
                       },
                "auth": self.Token(),
                "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())
                print "33[1;36;40m  update status successful 33[0m"
            except Exception  as e:
                print "33[1;36;40m  update status failed 33[0m"
                print e
        def Template(self):
            data=json.dumps({
                "jsonrpc": "2.0",
                "method": "template.get",
                "params": {
                      "output":"extend",
                       },
                "auth": self.Token(),
                "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())
                print "33[31m模板数量: %s33[0m"%len(response['result'])
                for template in response['result']:
                     print "33[1;36;40mTemplate ID: %s 33[0m "%template['templateid'],"	33[1;36;40mTemplate Name: %s 33[0m"%template['name']
            except Exception as e:
                print e
        def HostCreate(self):
            data=json.dumps({
                "jsonrpc": "2.0",
                "method": "host.create",
                "params": {
                    "host": sys.argv[2],
                    "interfaces": [
                        {
                            "type": 1,
                            "main": 1,
                            "useip": 1,
                            "ip": sys.argv[3],
                            "dns": "",
                            "port": "10050"
                        }
                    ],
                    "groups": [
                        {
                            "groupid": sys.argv[4]
                        }
                    ],
                    "templates": [
                        {
                            "templateid": "10001"
                        }
                    ],
                    "inventory_mode": 0,
                },
                "auth": self.Token(),
                "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())
                print "33[1;36;40m  create host successful 33[0m"
            except Exception  as e:
                print "33[1;36;40m  create host failed 33[0m"
                print e
        def HostDelete(self):
            data=json.dumps({
                "jsonrpc": "2.0",
                "method": "host.delete",
                "params": [
                 sys.argv[2]
                ],
                "auth": self.Token(),
                "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())
                print "33[1;36;40m delete host successful 33[0m"
            except Exception  as e:
                print "33[1;36;40m delete host failed 33[0m"
                print e
    def main():
         zabbix=ZabbixApi()
         parser=OptionParser()
         parser.add_option("-g","--listgroup",
                          dest="listgroup",
                          action="store_true",
                          help="Usage:python xxx -g ")
         parser.add_option("-c","--create",
                          dest="create",
                          action="store_true",
                          help="Usage:python xxx -c host  hostip groupid ")
         parser.add_option("-d","--delete",
                          dest="delete",
                          action="store_true",
                          help="Usage:python xxx -d hostid")
         parser.add_option("-t","--template",
                          dest="template",
                          action="store_true",
                          help="Usage:python xxx -t")
         parser.add_option("-i","--hostinfo",
                          dest="hostinfo",
                          action="store_true",
                          help="Usage:python xxx -i groupid")
         parser.add_option("-u","--update",
                          dest="updatestatus",
                          action="store_true",
                          help="Usage:python xxx -s ")
         options,args=parser.parse_args()
         if options.listgroup:
             zabbix.HostGroupList()
         if options.create:
             zabbix.HostCreate()
         if options.delete:
             zabbix.HostDelete()
         if options.template:
             zabbix.Template()
         if options.hostinfo:
             zabbix.HostInGroups()
         if options.updatestatus:
             zabbix.UpdateHostStatus()
    if  __name__=='__main__':
        main()

    注:标红的地方注意修改
  • 相关阅读:
    《Redis 垃圾回收》
    python-Day3-set 集合-counter计数器-默认字典(defaultdict) -可命名元组(namedtuple)-有序字典(orderedDict)-双向队列(deque)--Queue单项队列--深浅拷贝---函数参数
    Python--day4
    python--day2
    Python--day1
    Python字符串原理剖析------万恶的+号
    执行脚本传入参数
    字符编码
    css3动画与js动画的区别
    关于FormData及其用法
  • 原文地址:https://www.cnblogs.com/imcati/p/13577700.html
Copyright © 2020-2023  润新知