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添加点击事件,顺便复习一 ...
随机推荐
- GridView中显示时间日期格式问题
以下都是GridView基本常用的日期,时间格式 形式 语法 结果 注释 数字 {0:N2} 12.36 数字 {0:N0} 13 货币 {0:c2} $12.36 货币 {0:c4} $ ...
- C#开发微信门户及应用(13)-使用地理位置扩展相关应用
本文继续上一篇<C#开发微信门户及应用(12)-使用语音处理>,继续介绍微信的相关应用.我们知道,地理位置信息可以用来做很多相关的应用,除了我们可以知道用户所在的位置,还可以关联出一些地理 ...
- JavaWeb_day04搜索_乱码_路径_转发重定向_cookie
本文为博主辛苦总结,希望自己以后返回来看的时候理解更深刻,也希望可以起到帮助初学者的作用. 转载请注明 出自 : luogg的博客园 谢谢配合! 搜索功能 DAO层都是一些数据库的增删改查操作 Ser ...
- ECharts的简单使用过程
网页中经常要使用图表,以前使用的是highcharts插件,现在发现echarts使用起来和highcharts差不多,但是个人感觉echarts更酷炫,以下是echarts的使用过程,其实highc ...
- Redis(li)
一.Redis基础介绍 redis是一个key-value存储系统.和Memcached类似,它支持存储的value类型相对更多,包括string(字符串).list(链表).set(集合).zset ...
- GJM : Unity3D HIAR -【 快速入门 】 五、导出 Android 工程、应用
导出 Android 工程.应用 在开始之前,请务必先保存您的工程,同时确认您已经安装 Android SDK 和 JDK.安装操作请参考以下链接: 搭建开发环境 Step 1. 设置 Android ...
- Gulp自动添加版本号
推荐使用gulp-rev + gulp-rev-collector是比较方便的方法,结果如下: "/css/style.css" => "/dist/css/sty ...
- infopath发布的提示“无法解析SOAP消息”(The SOAP message cannot be parsed)问题解决方案
最近发现一个列表数据过大,每次发布infopath表单提示如下错误: 后来发现一个infopath表单通过list.asmx and Formsservice.asmx来进行发布的. This err ...
- Atitit.数据检索与网络爬虫与数据采集的原理概论
Atitit.数据检索与网络爬虫与数据采集的原理概论 1. 信息检索1 1.1. <信息检索导论>((美)曼宁...)[简介_书评_在线阅读] - dangdang.html1 1.2. ...
- AgilePoint实例属性修改
流程实例中的参数存放在WF_CUSTOM_ATTRS表的WF_CUSTOM_ATTRS字段,为ntext类型,里面存放的是XML,不能直接修改 update [APData].[dbo].[WF_ ...