python脚本对接zabbix API添加监控

一 环境

zabbix版本:4.0.6
python版本:Python 2.6.6

二 前提

创建机器时从xlsx文件导入,需要import xlrd
pip install xlrd

三 使用方法

1 excel表导入
image.png

表格中多个模板或多个主机组使用逗号分割

添加主机
[root@iZshvqfkb75a89Z test2]# python zabbix.py -L
主机数量: 0
hostgroup:  Linux servers   groupid : 2
Template Name :  Template OS Linux Active 
添加主机 :  192.168.1.202   id :[u'10326']
主机数量: 0
hostgroup:  Linux servers   groupid : 2
hostgroup:  Linux test  groupid : 17
Template Name :  Template OS Linux Active 
添加主机 :  192.168.1.203   id :[u'10327']
主机数量: 0
hostgroup:  Linux servers   groupid : 2
Template Name :  Template OS Linux Active 
Template Name :  Port monitor 21203 sshd 
Template Name :  Template Linux TCP Status 
添加主机 :  192.168.1.204   id :[u'10328']
2 其他

其中 -D 删除不能使用(不知道是不是对接zabbix4.0的API 不生效,暂时没有解决)

[root@iZshvqfkb75a89Z test2]# python zabbix.py 
usage: zabbix.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

四 pyhon脚本

#!/usr/bin/python
#coding:utf-8
  
import json
import urllib2
from urllib2 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://IP/zabbix/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", #web页面登录用户名
                                          "password": "zabbix" #web页面登录密码
                                          },
                               "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 用户认证失败,请检查 !\033[0m", e.code
            else:
                response = json.loads(result.read())
                result.close()
                #print response['result']
                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
                    })
            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()
                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 Status :\033[32m%s\033[0m \t Available :\033[31m%s\033[0m"%(host['hostid'],host['name'],status[host['status']],available[host['available']])
                        else:
                                print "HostID : %s\t HostName : %s\t Status :\033[32m%s\033[0m \t Available :\033[31m%s\033[0m"%(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,
                               })
              
            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:
                #print result.read()
                response = json.loads(result.read())
                result.close()
                #print response()
                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
                for template in response['result']:               
                    if len(templateName)==0:
                        print "template : \033[31m%s\033[0m\t  id : %s" % (template['name'], template['templateid'])
                    else:
                        self.templateID = response['result'][0]['templateid']
                        print "Template Name :  \033[31m%s\033[0m "%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 "\033[042m 添加主机组:%s\033[0m  hostgroupID : %s"%(hostgroupName,response['result']['groupids'])
 
 
        def host_create_excel(self,hostName,visibleName, hostip, hostgroupName, templateName,PskIdentity,PskValue):
            if self.host_get(hostip):
                print "\033[041m该主机已经添加!\033[0m"
                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": "10091"  #IP端口10051;SNMP端口161
                                          }
                                         ],
                                       "tls_connect": 2,  #psk链接
                                       "tls_accept": 2,   #主机允许从PSK
                                       "tls_psk_identity": PskIdentity,
                                       "tls_psk": PskValue,
                                       "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)
            except URLError as e:
                print "Error as ", e
            else:
                response = json.loads(result.read())
                result.close()
                print "添加主机 : \033[042m %s\033[0m \tid :\033[31m%s\033[0m" % (hostip, response['result']['hostids'])
                              
        def host_create(self, hostip, hostgroupName, templateName):
            if self.host_get(hostip):
                print "\033[041m该主机已经添加!\033[0m"
                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": "161"
                                          }
                                         ],
                                       "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)
            except URLError as e:
                print "Error as ", e
            else:
                response = json.loads(result.read())
                result.close()
                print "添加主机 : \033[42m%s\031[0m \tid :\033[31m%s\033[0m" % (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
                })
                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 '----主机现在状态------------'
                        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
                    })
 
            request = urllib2.Request(self.url,data)
            for key in self.header:
                request.add_header(key, self.header[key])
                  
            try:
                result = urllib2.urlopen(request)
            except Exception,e:
                print  e
            else:
 
                result.close()
                print "主机 \033[041m %s\033[0m  已经删除 !"%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('hosts1.xlsx')     #Excel名
                        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
                            hostgroup = workbook.sheets()[0].cell(row, 3).value
                            hosttemp = workbook.sheets()[0].cell(row, 4).value
                            pskidentity = workbook.sheets()[0].cell(row, 5).value
                            pskvalue = workbook.sheets()[0].cell(row, 6).value
                            # print workbook.sheets()[0].cell(row, 0).value
                            # print workbook.sheets()[0].cell(row, 1).value
                            # print workbook.sheets()[0].cell(row, 2).value
                            # print workbook.sheets()[0].cell(row, 3).value
                            # print workbook.sheets()[0].cell(row, 4).value
                            # print workbook.sheets()[0].cell(row, 5).value
                            # print workbook.sheets()[0].cell(row, 6).value
                            zabbix.host_create_excel(hostname,visible,hostip,hostgroup, hosttemp,pskidentity,pskvalue)

参考:

https://www.cnblogs.com/momoshouhu/p/8053907.html
https://www.zabbix.com/documentation/4.0/zh/manual/api/reference/host/object

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 159,458评论 4 363
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,454评论 1 294
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 109,171评论 0 243
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 44,062评论 0 207
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,440评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,661评论 1 219
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,906评论 2 313
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,609评论 0 200
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,379评论 1 246
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,600评论 2 246
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,085评论 1 261
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,409评论 2 254
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,072评论 3 237
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,088评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,860评论 0 195
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,704评论 2 276
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,608评论 2 270

推荐阅读更多精彩内容