zabbix利用api批量添加item,并且批量配置添加graph
关于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 '''
zabbix利用api批量添加item,并且批量配置添加graph的更多相关文章
- 利用ListView批量删除item
利用CheckBox选中一个或多个item,最后批量删除它们. 程序运行效果图如下: package com.test.adapter; import java.util.ArrayList; imp ...
- Zabbix实战-简易教程(8)--添加item
一.术语 1.1 Item概念 Item是从主机里面获取的所有数据.通常情况下 item称为监控项,例如我们host加入了 zabbix 监控,我们需要监控它的内存.CPU信息,那么获取的CPU或内存 ...
- 利用struts2进行单个文件,批量文件上传,ajax异步上传以及下载
利用struts2进行单个文件,批量文件上传,ajax异步上传以及下载 1.页面显示代码 <%@ page language="java" import="java ...
- Zabbix的API的使用
上一篇:Zabbix低级主动发现之MySQL多实例 登录请求(返回一个token,在后面的api中需要用到) curl -s -X POST -H 'Content-Type:application/ ...
- zabbix java api
zabbix java api zabbix官方的api文档地址:https://www.zabbix.com/documentation/3.0/manual/api Zabbix功能 概观 Zab ...
- zabbix 利用python脚本实现钉钉告警
Zabbix 利用python脚本实现钉钉告警 1.安装python3.6环境 2.创建python脚本 cd local/zabbix-4.0.3/share/zabbix/alertscripts ...
- C#基础第七天-作业答案-利用面向对象的思想去实现名片-动态添加
class Card { private string name; public string Name { get { return name; } set { name = value; } } ...
- PHP批量写入数据、批量删除数据
批量插入可以参考$sql = "insert into data (id,ip,data) values ";for($i=0;$i<100;$i++){$sqls[]=& ...
- Android 高级UI设计笔记20:RecyclerView 的详解之RecyclerView添加Item点击事件
1. 引言: RecyclerView侧重的是布局的灵活性,虽说可以替代ListView但是连基本的点击事件都没有,这篇文章就来详细讲解如何为RecyclerView的item添加点击事件,顺便复习一 ...
随机推荐
- C语言辗转相除法求2个数的最小公约数
辗转相除法最大的用途就是用来求两个数的最大公约数. 用(a,b)来表示a和b的最大公约数. 有定理: 已知a,b,c为正整数,若a除以b余c,则(a,b)=(b,c). (证明过程请参考其它资料) 例 ...
- python 学习笔记 -logging模块(日志)
模块级函数 logging.getLogger([name]):返回一个logger对象,如果没有指定名字将返回root loggerlogging.debug().logging.info().lo ...
- HTML5 Canvas玩转酷炫大波浪进度图
如上图所见,本文就是要实现上面那种效果. 由于最近AlloyTouch要写一个下拉刷新的酷炫loading效果.所以首选大波浪进度图. 首先要封装一下大波浪图片进度组件.基本的原理是利用Canvas绘 ...
- CartO
Carto documentation The following is a list of properties provided in CartoCSS that you can apply to ...
- emoji哈哈哈哈
Unicode 官网上的FAQ令人发笑,啊哈哈哈 Q: What are the most popular emoji characters? Q: Do emoji characters have ...
- 【转】Android SDK Samples,学习Android的好方法
转载地址:http://blog.csdn.net/rowland001/article/details/50886288 从今天开始呢,我要开始学习Google家自己出的Android代码示例,总觉 ...
- IOS 杂笔-12(类别de巧用 有便于Frame的操作)
在实际开发中很多时候我们都为了控件frame的操作焦头烂额. 例如:我们只想要获取view的width. 我们可以这么操作:view.frame.size.width 有时我们想要改变view的wid ...
- Redis五种基本数据结构
1.字符串 示例: 2.列表 示例: 3.集合 示例: 4.散列 示例: 5.有序集合 待续...
- 如何定义好一个符合规范的url
描述 进公司没有多久遇到一个问题,定义的url会被大神吐槽说是很渣.之前从来没有注意这块,今天把我们团队的url规范分享给大家. 为什么需要URL规范化 1.网站URL和结构已经成为网站搜索引擎友好的 ...
- [Erlang 0118] Erlang 杂记 V
我在知乎回答问题不多,这个问题: "对你职业生涯帮助最大的习惯是什么?它是如何帮助你的?",我还是主动回答了一下. 做笔记 一开始笔记软件做的不好的时候就发邮件给自己, ...