关于zabbix的API见,zabbixAPI
1item批量添加
我是根据我这边的具体情况来做的,本来想在模板里面添加item,但是看了看API不支持,只是支持在host里面添加,所以我先在一个host里面添加,然后在将item全部移动到模板里。
具体步骤就不说了,直接上代码:
为了快速完成,代码写的有点乱,也没怎么处理异常,算是第一版吧,有时间在优化 1 #!/usr/bin/env python
#-*- coding: utf- -*- import json
import sys
import urllib2
import argparse
from urllib2 import URLError reload(sys)
sys.setdefaultencoding('utf-8') class zabbix_api:
def __init__(self):
#self.url
#self.url = 'http://zabbix.weimob.com/api_jsonrpc.php'
self.url = 'http://xxxxxx/api_jsonrpc.php' #zabbix地址
self.header = {"Content-Type":"application/json"}
def user_login(self):
data = json.dumps({
"jsonrpc": "2.0",
"method": "user.login",
"params": {
"user": "admin", #账号
"password": "admin" #密码
},
"id":
}) 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()
#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",
#"output": "selectInterfaces",
#"filter":{"host":""}
"filter":{"host":hostName}
},
"auth": self.user_login(),
"id":
})
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 reqponse
result.close() #print "主机数量: \033[31m%s\033[0m"%(len(response['result']))
#print response
#print response['result']
#print response['result']['templateid']
for host in response['result']:
#print host['hostid']
c=host['hostid']
return c def host_interin(self,host_id): data=json.dumps({
"jsonrpc": "2.0",
"method": "hostinterface.get",
"params": {
"output": "extend",
#"hostids": "",
"hostids": host_id,
#"filter":{"host":hostip}, },
"auth": self.user_login(),
"id":
})
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 reqponse
result.close()
#print response
#print response['result']
for host in response['result']:
b=host['interfaceid']
return b def create_item(self,hostid,interfaceid,key_name,key):
#def create_item(self):
data = json.dumps({
"jsonrpc": "2.0",
"method": "item.create",
"params":{
#"name": "pingsd",
"name": key_name,
#"key_": "pingsd_Ip",
"key_":key,
#"hostid": "",
"hostid": hostid,
#"interfaceid": "",
"interfaceid": interfaceid,
#"templateid": "",
"type": ,
"value_type": ,
"date_type": ,
"delay": ,
"history": ,
"trends": ,
"status": ,
"applications": [
""
],
},
"auth": self.user_login(),
"id":
})
request = urllib2.Request(self.url, data)
for key in self.header:
request.add_header(key, self.header[key]) try:
result = urllib2.urlopen(request)
response = json.loads(result.read())
result.close()
print 'success'
print response
#for host in response['result']:
except Exception,e:
print e
def get_application(self):
data=json.dumps({
"jsonrpc": "2.0",
"method": "application.get",
"params": {
"output": "extend",
"hostids": "",
"sortfield": "name"
},
"auth": self.user_login(),
"id":
}) 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 reqponse
result.close()
print response
for host in response['result']:
print host['applicationid']
print host['name']
def graph_create(self,ping_id,loss_id,ping_name):
data = json.dumps({
"jsonrpc": "2.0",
"method": "graph.create",
"params": {
"name": ping_name,
"width": ,
"height": ,
"gitems": [
{
"itemid": ping_id,
"color": "00AA00",
"sortorder": ""
},
{
"itemid": loss_id,
"color": "3333FF",
"sortorder": ""
}
]
},
"auth": self.user_login(),
"id":
})
request = urllib2.Request(self.url, data)
for key in self.header:
request.add_header(key, self.header[key]) try:
result = urllib2.urlopen(request)
response = json.loads(result.read())
result.close()
print 'success'
print response
except Exception,e:
print e
def get_item_id(self,hostid):
data=json.dumps({ "jsonrpc": "2.0",
"method": "item.get",
"params": {
"output": "extend",
"hostids": hostid,
#"search": {
#"key_": "system"
# },
"sortfield": "name"
},
"auth": self.user_login(),
"id": ,
}) 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 reqponse
result.close()
print response
for host in response['result']:
print host['itemid'],host['name'] #print obj = zabbix_api()
#ret=obj.host_get('txgzvpc2')
#print ret
#obj.get_item_id(ret)
print "===================创建graph========================="
with open("ping_or") as f:
ping_id1=[(r.rstrip("\r\n")) for r in f.readlines()]
with open("loss_or") as f:
loss_id1=[(r.rstrip("\r\n")) for r in f.readlines()]
with open('file1') as f:
ip=[(r.rstrip("\r\n")) for r in f.readlines()]
for i in range(len(ping_id1)):
print ping_id1[i],loss_id1[i],ip[i]
obj.graph_create(ping_id1[i],loss_id1[i],ip[i])
print "=====================创建graph=============================="
#说明:file里面是graph的名字。ping_or,losss_or分别是itemid
#for key in hosfile: # print key
# print ip
#obj.graph_create(key,hosfile[key]) #ret1=obj.host_interin(ret)
#print ret1
#obj.get_application()
#obj.create_item() '''
file1=sys.argv[]
file2=sys.argv[]
file3=sys.argv[] ip=open(file1,'r').readline().strip('\r\n')
ping_id1=open(file2,'r').readline().strip('\r\n')
loss_id1=open(file3,'r').readline().strip('\r\n')
ret=obj.host_get('txgzvpc25')
print ret
ret1=obj.host_interin(ret)
print ret1
'''
'''
print "==============添加item======================================="
if __name__ == '__main__':
obj = zabbix_api()
ret=obj.host_get('alivpx11-88') #主机的hostname
print ret
ret1=obj.host_interin(ret)
print ret1
with open ('file','rb') as f: #file里面是key和那个名字,我这里为了方便,让他们一样了
for i in f.readlines():
obj.create_item(ret,ret1,i.strip('\r\n'),i.strip('\r\n')) print "==============添加item======================================="
''' ''' def graph_create(self):
data = json.dumps({
"jsonrpc": "2.0",
"method": "graph.create",
"params": {
"name": "MySQL bandwidth",
"width": ,
"height": ,
"gitems": [
{
"itemid": "",
"color": "00AA00",
"sortorder": ""
},
{
"itemid": "",
"color": "3333FF",
"sortorder": ""
}
]
},
"auth": "038e1d7b1735c6a5436ee9eae095879e",
"id":
})
request = urllib2.Request(self.url, data)
for key in self.header:
request.add_header(key, self.header[key]) try:
result = urllib2.urlopen(request)
response = json.loads(result.read())
result.close()
print 'success'
except Exception,e:
print e
'''
'''
if __name__ == '__main__': obj = zabbix_api()
#ret=obj.create_item()
#print ret
ret=obj.host_get('txgzvpc1-1')
print ret
#obj.host_interin('x.x.x.x')
'''
'''
def get_template_id(self):
data=json.dumps({
"jsonrpc": "2.0",
"method": "template.get",
"params": {
"output": "extend",
"filter": {
"host": [
"ceshitemplate",
]
}
},
"auth": self.user_login(),
"id":
}) 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 reqponse
result.close()
print response
for host in response['result']:
print host['templateid'] def get_application(self):
data=json.dumps({
"jsonrpc": "2.0",
"method": "application.get",
"params": {
"output": "extend",
"hostids": "",
"sortfield": "name"
},
"auth": self.user_login(),
"id":
}) 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 reqponse
result.close()
print response
for host in response['result']:
print host['applicationid']
print host['name']
'''
#obj.host_interin('x.x.x.x')
#obj.get_template_id()
#obj.get_application()
285 '''
286 hosfile=dict()
287 with open("ping_or") as f:
288 ping_id1=[(r.rstrip("\r\n")) for r in f.readlines()]
289 print ping_id1
290
291 with open("loss_or") as f:
292 loss_id1=[(r.rstrip("\r\n")) for r in f.readlines()]
293 print loss_id1
294 for i in range(len(ping_id1)):
295 hosfile[ping_id1[i]]=loss_id1[i]
296
297 print hosfile
298 '''