Python读取Excel调用Zabbix API批量添加主机脚本

对于有大量主机需要录入zabbix监控时,我们通常有三种方法:

1、手动一台台添加,费时费力(不推荐);

2、利用zabbix自发现功能,配置好规则即可,不过有时候会不准确(常用);

3、通过python调用zabbix API添加,需要会python语言,门槛偏高,添加准确。

对于前两种方法比较常用也很简单,今天给大家分享个调用zabbix API添加的python脚本。

Python读取Excel调用Zabbix API批量添加主机脚本

Excel格式:A-F列分别是hostName、visibleName、hostIp、hostgroupName、templateName1、templateName2

#!/usr/bin/env python
#-*- coding: utf-8 -*-

import json
import sys
import urllib2
import xlrd

from urllib2 import URLError


class zabbix_api:
def __init__(self):

#http://192.168.1.10是zabbix前端地址,api_jsonrpc.php是调用API的PHP脚本
self.url = 'http://192.168.1.10/api_jsonrpc.php'
self.header = {"Content-Type":"application/json"}
def user_login(self):
data = json.dumps({
"jsonrpc": "2.0",
"method": "user.login",
"params": {

#zabbix登录的用户名和密码
"user": "admin",
"password": "123456"
},
"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 认证失败,请检查URL !\033[0m",e.code
except KeyError as e:
print "\033[041m 认证失败,请检查用户名密码 !\033[0m",e
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()
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()
if not len(response['result']):
print "\033[041m %s \033[0m is not exist" % hostgroupName
return False
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": {
"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()
self.templateID = response['result'][0]['templateid']
return response['result'][0]['templateid']

#创建主机

def host_create(self, hostName,visibleName,hostIp, hostgroupName, templateName1,templateName2):
data = json.dumps({
"jsonrpc":"2.0",
"method":"host.create",
"params":{
"host": hostName,
"name": visibleName,
"interfaces": [
{
"type": 1,
"main": 1,
"useip": 1,
"ip": hostIp,
"dns": "",
"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! Group:%s" % (hostip,hostgroup)
print templateName1
print templateName2
print response
self.hostid = response['result']['hostids']
return response['result']['hostids']

 

if __name__ == "__main__":
zabbix=zabbix_api()

#lists.xls为需要导入的excel名称

workbook = xlrd.open_workbook('lists.xls')

#获取excel里的数据
table = workbook.sheets()[0]
nrows = table.nrows

for row in range(nrows):
hostname=table.cell(row,0).value
visible=table.cell(row,1).value
hostip=table.cell(row,2).value
hostgroup=table.cell(row,3).value
hosttemp=table.cell(row,4).value
hosttemp1=table.cell(row,5).value

hostnameGet=zabbix.host_get(hostname)

#判断主机名如果在zabbix上不存在则添加
if hostnameGet.strip()=='':
zabbix.host_create(hostname,visible,hostip,hostgroup,hosttemp,hosttemp1)
else:
print "%s have exist! Cannot recreate !\n" % hostnameGet

weinxin
聂扬帆博客
一个分享IT运维相关工作经验和实战技巧的个人博客

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

目前评论:1   其中:访客  1   博主  0

  1. avatar 春熙路 2

    进来看看