ZABBIX通过PYTHON脚本批量添加客户端

PYTHON脚本的代码网上找的,URL改成ZABBIX服务器的地址加上ZABBIX的API接口api_jsonrpc.php,用户名密码也改成实际的ZABBIX用户名和密码即可

[root@v73 pys]# cat 2.py 
#!/usr/local/bin/python 
#coding:utf-8 
  
import json 
import urllib2 
from urllib2 import URLError 
import sys 
import xlrd
  
class ZabbixTools: 
    def __init__(self): 
        self.url = 'http://192.168.99.73/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": "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 "Auth Failed, please Check your name and password:", e.code 
        else: 
            response = json.loads(result.read()) 
            result.close() 
            self.authID = response['result'] 
            return self.authID 
          
    def host_get(self,hostName): 
        data = json.dumps({ 
                           "jsonrpc":"2.0", 
                           "method":"host.get", 
                           "params":{ 
                                     "output":["hostid","name"], 
                                     "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()) 
            result.close() 
            print "Number Of %s: " % hostName, len(response['result']) 
            lens=len(response['result']) 
            if lens > 0:
                return response['result'][0]['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.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() 
 
            lens=len(response['result']) 
            if lens > 0:
                self.hostgroupID = response['result'][0]['groupid']
                return response['result'][0]['groupid']
            else:
                print "no GroupGet result"
                return ""
 
              
    def template_get(self, templateName): 
        data = json.dumps({ 
                           "jsonrpc":"2.0", 
                           "method": "template.get", 
                           "params": { 
                                      "output": "extend", 
                                      "filter": { 
                                                 "host": [ 
                                                          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() 
            self.templateID = response['result'][0]['templateid'] 
            return response['result'][0]['templateid'] 
                  
    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)
                                                          
                                                    },
                                                    { 
                                                         
                                                        "templateid": self.template_get(templateName2) 
                                                    } 
                                                  ], 
                                     }, 
                           "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 "host : %s is created!   id is  %s\n" % (hostip, response['result']['hostids'][0]) 
            self.hostid = response['result']['hostids'] 
            return response['result']['hostids'] 
          
    def proxy_get(self, ProxyName):
        data = json.dumps({
                           "jsonrpc":"2.0",
                           "method": "proxy.get",
                           "params": {
                                      "output": "extend",
                                      "selectInterface": "extend",
                                      "filter": {
                                          "host": [ ProxyName, ]
                                      }
                                      },
                           "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()
            self.templateID = response['result'][0]['proxyid']
            return response['result'][0]['proxyid']
 
 
         
                  
                  
if __name__ == "__main__": 
          
    test = ZabbixTools() 
 
    workbook = xlrd.open_workbook('test.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

 

excel的内容,从左至右为:主机名,显示名,IP,DNS名称,agent代理程序,主机群组,模板1,模板2

执行脚本:

再到ZABBIX的WEB控制台看,主机已经被添加到相应的群组,和链接到模板了

 

对源码稍作修改,符合自定义的需求:

[root@v73 pys]# cat auto.py 
#!/usr/local/bin/python 
#coding:utf-8 
  
import json 
import urllib2 
from urllib2 import URLError 
import sys 
import getpass
  
class ZabbixTools: 
    def __init__(self,urls,unames,pwds): 
        self.url = 'http://'+urls+'/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": unames, 
                                      "password": pwds 
                                      }, 
                           "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() 
            self.authID = response['result'] 
            return self.authID 
          
    def host_get(self,hostName): 
        data = json.dumps({ 
                           "jsonrpc":"2.0", 
                           "method":"host.get", 
                           "params":{ 
                                     "output":["hostid","name"], 
                                     "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()) 
            result.close() 
            print "Number Of %s: " % hostName, len(response['result']) 
            lens=len(response['result']) 
            if lens > 0:
                return response['result'][0]['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.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() 
 
            lens=len(response['result']) 
            if lens > 0:
                self.hostgroupID = response['result'][0]['groupid']
                return response['result'][0]['groupid']
            else:
                print "no GroupGet result"
                return ""
 
              
    def template_get(self, templateName): 
        data = json.dumps({ 
                           "jsonrpc":"2.0", 
                           "method": "template.get", 
                           "params": { 
                                      "output": "extend", 
                                      "filter": { 
                                                 "host": [ 
                                                          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() 
            self.templateID = response['result'][0]['templateid'] 
            return response['result'][0]['templateid'] 
                  
    def host_create(self, hostName,visibleName,hostIp,dnsName,proxyName, hostgroupName, templateName1): 
        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.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 "host : %s is created!   id is  %s\n" % (hostip, response['result']['hostids'][0]) 
            self.hostid = response['result']['hostids'] 
            return response['result']['hostids'] 
          
    def proxy_get(self, ProxyName):
        data = json.dumps({
                           "jsonrpc":"2.0",
                           "method": "proxy.get",
                           "params": {
                                      "output": "extend",
                                      "selectInterface": "extend",
                                      "filter": {
                                          "host": [ ProxyName, ]
                                      }
                                      },
                           "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()
            self.templateID = response['result'][0]['proxyid']
            return response['result'][0]['proxyid']
 
 
         
                  
                  
if __name__ == "__main__": 
    unames=raw_input('zabbixusername:')
    pwds=getpass.getpass('zabbixpassword:')
    if len(sys.argv) < 2:
        urls="yourzabbix.com"
    else:
        urls=sys.argv[1] 
    test = ZabbixTools(urls,unames,pwds) 
    myfile=open("ips.csv",'r')
    i=0
    for line in myfile:
        if i==0:
            pass
        else:
            infos=line.split(",")
            hostname=infos[0].strip()
            visible=infos[1].strip()
            hostip=infos[2].strip()
            dnsname=infos[3].strip()
            proxy=infos[4].strip()
            hostgroup=infos[5].strip()
            hosttemp=infos[6].strip() 
     
            hostgroup=hostgroup.strip()
            hostnameGet=test.host_get(hostname)
            if hostnameGet.strip()=='':
                test.host_create(hostname,visible,hostip,dnsname,proxy,hostgroup,hosttemp)
            else:
                print "%s have exist! Cannot recreate !\n" % hostnameGet
        i=i+1

采用CSV的文本编辑

脚本跑起来差不多

 

zabbix的官方文档对一些方法的说明:

https://www.zabbix.com/documentation/4.0/manual/api/reference/host/get

已标记关键词 清除标记
相关推荐
【为什么还需要学习C++?】 你是否接触很多语言,但从来没有了解过编程语言的本质? 你是否想成为一名资深开发人员,想开发别人做不了的高性能程序? 你是否经常想要窥探大型企业级开发工程的思路,但苦于没有基础只能望洋兴叹?   那么C++就是你个人能力提升,职业之路进阶的不二之选。 【课程特色】 1.课程共19大章节,239课时内容,涵盖数据结构、函数、类、指针、标准库全部知识体系。 2.带你从知识与思想的层面从0构建C++知识框架,分析大型项目实践思路,为你打下坚实的基础。 3.李宁老师结合4大国外顶级C++著作的精华为大家推出的《征服C++11》课程。 【学完后我将达到什么水平?】 1.对C++的各个知识能够熟练配置、开发、部署; 2.吊打一切关于C++的笔试面试题; 3.面向物联网的“嵌入式”和面向大型化的“分布式”开发,掌握职业钥匙,把握行业先机。 【面向人群】 1.希望一站式快速入门的C++初学者; 2.希望快速学习 C++、掌握编程要义、修炼内功的开发者; 3.有志于挑战更高级的开发项目,成为资深开发的工程师。 【课程设计】 本课程包含3大模块 基础篇 本篇主要讲解c++的基础概念,包含数据类型、运算符等基本语法,数组、指针、字符串等基本词法,循环、函数、类等基本句法等。 进阶篇 本篇主要讲解编程中常用的一些技能,包含类的高级技术、类的继承、编译链接和命名空间等。 提升篇: 本篇可以帮助学员更加高效的进行c++开发,其中包含类型转换、文件操作、异常处理、代码重用等内容。
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页