使用Zabbix API自动添加主机

1.前言

最近需要在服务器集群上添加Zabbix Agent来监控数据,大概需要部署1000台。每一台都需要在Zabbix Web上添加主机,以查看数据和配置信息,这个数量的主机信息,要是全手动添加,那一天到晚啥都不用做,光点击鼠标添加了。于是想看看有啥自动化脚本可用,看到了Zabbix API,有了一些方向。可以把配置信息都写进CSV里,使用Python脚本读取,借助API自动添加,省时省力!

2.Python脚本代码

话不多说,直接上代码:

添加脚本 
addhost.py
	#coding:utf-8
	import json
	import urllib2
	from urllib2 import URLError
	import sys
	import xlrd
	# 测试ok
	class ZabbixTools:
	    def __init__(self):
	        self.url = 'http://172.20.10.3/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'] 
	    # 创建host
	    #def host_create(self, hostName,visibleName,hostIp,dnsName,proxyName, hostgroupName, templateName1, templateName2):
	    def host_create(self, hostName,visibleName,hostIp, hostgroupName, templateName1, port):
	        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": "",
	                                                            "port": port
	                                                        }
	                                                    ],
	                                    "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'] 
	# 程序的入口                
	if __name__ == "__main__":
	    # 实例化ZabbixTools对象   
	    test = ZabbixTools() 
	    #result = test.host_get('node5.chinasoft.com')
	    #print result
	    # 获取host列表
	    workbook = xlrd.open_workbook('host_list.xls')
	    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
	        hostport=workbook.sheets()[0].cell(row,5).value
	        hostgroup=hostgroup.strip()
	        hostnameGet=test.host_get(hostname)
	        print hostname + ',' + visible + ',' + hostip + ',' + hostgroup + ',' +  hosttemp
	        test.host_create(hostname,visible,hostip,hostgroup,hosttemp,hostport)

3.解释和说明

代码应该很好理解了,主要还是读取CSV和使用API。可能需要安装xlrd,联网的情况下直接yum安装,集群没网也可以去官网下一个安装包解压安装。
给一个CSV样例,照着这个写好配置信息就好了:
样例

你可能感兴趣的:(Zabbix)