所需环境

  1. Python 3
  2. ZABBIX 3.0+
  3. PIP 环境

安装Python环境:

[root@Sunday ~]# yum -y install epel-release
[root@Sunday ~]# yum -y install python3 pip3
[root@Sunday ~]# pip install xlrd

表格所需字段

主机名可见主机名主机IP主机群组链接模板

举个栗子

Route_01Route_01172.31.64.11网络设备Template OS Route

编写代码

[root@Sunday ~]# vim zbx_add_host.py 

#!/usr/bin/python3
#coding:utf-8
 
import json
import urllib.request
from urllib.error import URLError
import sys,argparse
import xlrd
 
defaultencoding = 'utf-8'
if sys.getdefaultencoding() != defaultencoding:
    reload(sys)
    sys.setdefaultencoding(defaultencoding)
 
class zabbix_api:
        def __init__(self):
            self.url = 'http://zabbix.itan90.cn/api_jsonrpc.php' #修改URL
            self.header = {"Content-Type":"application/json"}
 
 
        def user_login(self):
            data = json.dumps({
                               "jsonrpc": "2.0",
                               "method": "user.login",
                               "params": {
                                          "user": "Admin",
                                          "password": "sa123"
                                          },
                               "id": 0
                               })
 
            # data = urllib.parse.quote_plus(data).encode("utf-8")
            data = data.encode("utf-8")
            request = urllib.request.Request(self.url, data)
            for key in self.header:
                request.add_header(key, self.header[key])
 
            try:
                result = urllib.request.urlopen(request)
            except URLError as e:
                print ("用户认证失败,请检查 !", 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": "extend",
                              "filter":{"host":hostName}
                              },
                    "auth": self.user_login(),
                    "id": 1
                    })
            data = data.encode("utf-8")
            request = urllib.request.Request(self.url,data)
            for key in self.header:
                request.add_header(key, self.header[key])
 
            try:
                result = urllib.request.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()
                print ("主机数量: %s"%(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 Status :%s \t Available :%s"%(host['hostid'],host['name'],status[host['status']],available[host['available']]))
                        else:
                                print ("HostID : %s\t HostName : %s\t Status :%s \t Available :%s"%(host['hostid'],host['name'],status[host['status']],available[host['available']]))
                                return host['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,
                               })
            data = data.encode("utf-8")
            request = urllib.request.Request(self.url,data)
            for key in self.header:
                request.add_header(key, self.header[key])
 
            try:
                result = urllib.request.urlopen(request)
            except URLError as e:
                print ("Error as ", e)
            else:
                #print result.read()
                response = json.loads(result.read())
                result.close()
                #print response()
                for group in response['result']:
                        if  len(hostgroupName)==0:
                                print ("hostgroup:  %s \tgroupid : %s" %(group['name'],group['groupid']))
                        else:
                                print ("hostgroup:  %s\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,
                               })
 
            data = data.encode("utf-8")
            request = urllib.request.Request(self.url, data)
            for key in self.header:
                request.add_header(key, self.header[key])
 
            try:
                result = urllib.request.urlopen(request)
            except URLError as e:
                print ("Error as ", e)
            else:
                response = json.loads(result.read())
                result.close()
                #print response
                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  %s is exist !"%hostgroupName)
                sys.exit(1)
            data = json.dumps({
                              "jsonrpc": "2.0",
                              "method": "hostgroup.create",
                              "params": {
                              "name": hostgroupName
                              },
                              "auth": self.user_login(),
                              "id": 1
                              })
            data = data.encode("utf-8")
            request=urllib.request.Request(self.url,data)
 
            for key in self.header:
                request.add_header(key, self.header[key])
 
            try:
                result = urllib.request.urlopen(request)
            except URLError as e:
                print ("Error as ", e)
            else:
                response = json.loads(result.read())
                result.close()
                print ("添加主机组:%s  hostgroupID : %s"%(hostgroupName,response['result']['groupids']))
 
 
        def host_create_andy(self,hostName,visibleName, hostip, hostgroupName, templateName):
            if self.host_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,
                                         "name": visibleName,
                                         "interfaces": [
                                         {
                                         "type": 1,    #1:表示IP;2表示SNMP
                                         "main": 1,
                                         "useip": 1,
                                         "ip": hostip,
                                         "dns": "",
                                         "port": "10050"  #IP端口10051;SNMP端口161
                                          }
                                         ],
                                       "groups": group_list,
                                       "templates": template_list,
                                         },
                               "auth": self.user_login(),
                               "id":1
            })
            data = data.encode("utf-8")
            request = urllib.request.Request(self.url, data)
            for key in self.header:
                request.add_header(key, self.header[key])
 
            try:
                result = urllib.request.urlopen(request)
            except URLError as e:
                print ("Error as ", e)
            else:
                response = json.loads(result.read())
                result.close()
            try:
                print ("添加主机 :%s \tid :%s" % (hostip, response['result']['hostids']))
            except KeyError as e:
                print ("信息 :%s \tid :%s" % (hostip, response['error']['data']))
 
        def host_create(self, hostip, hostgroupName, templateName):
            if self.host_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": hostip,
                                         "interfaces": [
                                         {
                                         "type": 2,
                                         "main": 1,
                                         "useip": 1,
                                         "ip": hostip,
                                         "dns": "",
                                         "port": "10050"
                                          }
                                         ],
                                       "groups": group_list,
                                       "templates": template_list,
                                         },
                               "auth": self.user_login(),
                               "id":1
            })
            data = data.encode("utf-8")
            request = urllib.request.Request(self.url, data)
            for key in self.header:
                request.add_header(key, self.header[key])
 
            try:
                result = urllib.request.urlopen(request)
            except URLError as e:
                print ("Error as ", e)
            else:
                response = json.loads(result.read())
                result.close()
                print ("添加主机 : %s \tid :%s" % (hostip, response['result']['hostids']))
 
 
 
        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
                })
                data = data.encode("utf-8")
                request = urllib.request.Request(self.url,data)
                for key in self.header:
                        request.add_header(key, self.header[key])
                try:
                        result = urllib.request.urlopen(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,hostid):
            hostid_list=[]
            #print type(hostid)
            for i in hostid.split(','):
                var = {}
                var['hostid'] = self.host_get(i)
                hostid_list.append(var)
            data=json.dumps({
                                "jsonrpc": "2.0",
                                "method": "host.delete",
                                "params": hostid_list,
                    "auth": self.user_login(),
                    "id": 1
                    })
 
            data = data.encode("utf-8")
            request = urllib.request.Request(self.url,data)
            for key in self.header:
                request.add_header(key, self.header[key])
 
            try:
                result = urllib.request.urlopen(request)
            except Exception as e:
                print  (e)
            else:
 
                result.close()
                print ("主机  %s  已经删除 !"%hostid)
 
 
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=3,metavar=('192.168.2.1', 'test01,test02', 'Template01,Template02'),help='添加主机,多个主机组或模板使用分号')
        parser.add_argument('-d','--disable',dest='disablehost',nargs=1,metavar=('192.168.2.1'),help='禁用主机')
        parser.add_argument('-L','--allin',dest='allin',nargs='?',default='allin',help='从Excel批量导入主机')
        parser.add_argument('-D','--delete',dest='deletehost',nargs='+',metavar=('192.168.2.1'),help='删除主机,多个主机之间用分号')
        parser.add_argument('-v','--version', action='version', version='%(prog)s 1.0')
        if len(sys.argv)==1:
                print (parser.print_help())
        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])
                if args.disablehost:
                        zabbix.host_disable(args.disablehost)
                if args.deletehost:
                        zabbix.host_delete(args.deletehost[0])
                if args.allin != 'allin':
                        workbook = xlrd.open_workbook('zabbix_host_add.xlsx')     #Excel名
                        for row in range(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
                            hostgroup = workbook.sheets()[0].cell(row, 3).value
                            hosttemp = workbook.sheets()[0].cell(row, 4).value
 
                            zabbix.host_create_andy(hostname,visible,hostip,hostgroup, hosttemp)

修改代码

  1. 修改第19行的URL,可以直接访问的,例如: http://192.168.1.1/zabbix/api_jsonrpc.php
  2. 修改第28、29行的ZABBIX账号密码,对群组有修改的权限
  3. 修改第214行的选项: 1表示使用主机AGENT,2使用SNMP协议
  4. 修改第219行的端口: 被监控端

运行代码

  1. 主机表的命名为:zabbix_host_add.xlsx
  2. 运行

    [root@Sunday]# python3 zbx_add_host.py -L
    

脚本选项:

usage: zbx_add_host.py [options]

zabbix api

optional arguments:
  -h, --help            show this help message and exit
  -H [LISTHOST], --host [LISTHOST]
                        查询主机
  -G [LISTGROUP], --group [LISTGROUP]
                        查询主机组
  -T [LISTTEMP], --template [LISTTEMP]
                        查询模板信息
  -A ADDGROUP, --add-group ADDGROUP
                        添加主机组
  -C 192.168.2.1 test01,test02 Template01,Template02, --add-host 192.168.2.1 test01,test02 Template01,Template02
                        添加主机,多个主机组或模板使用分号
  -d 192.168.2.1, --disable 192.168.2.1
                        禁用主机
  -L [ALLIN], --allin [ALLIN]
                        从Excel批量导入主机
  -D 192.168.2.1 [192.168.2.1 ...], --delete 192.168.2.1 [192.168.2.1 ...]
                        删除主机,多个主机之间用分号
  -v, --version         show program's version number and exit
None
Last modification:December 4th, 2019 at 08:07 pm