关于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']:
#print
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的更多相关文章

  1. 利用ListView批量删除item

    利用CheckBox选中一个或多个item,最后批量删除它们. 程序运行效果图如下: package com.test.adapter; import java.util.ArrayList; imp ...

  2. Zabbix实战-简易教程(8)--添加item

    一.术语 1.1 Item概念 Item是从主机里面获取的所有数据.通常情况下 item称为监控项,例如我们host加入了 zabbix 监控,我们需要监控它的内存.CPU信息,那么获取的CPU或内存 ...

  3. 利用struts2进行单个文件,批量文件上传,ajax异步上传以及下载

    利用struts2进行单个文件,批量文件上传,ajax异步上传以及下载 1.页面显示代码 <%@ page language="java" import="java ...

  4. Zabbix的API的使用

    上一篇:Zabbix低级主动发现之MySQL多实例 登录请求(返回一个token,在后面的api中需要用到) curl -s -X POST -H 'Content-Type:application/ ...

  5. zabbix java api

    zabbix java api zabbix官方的api文档地址:https://www.zabbix.com/documentation/3.0/manual/api Zabbix功能 概观 Zab ...

  6. zabbix 利用python脚本实现钉钉告警

    Zabbix 利用python脚本实现钉钉告警 1.安装python3.6环境 2.创建python脚本 cd local/zabbix-4.0.3/share/zabbix/alertscripts ...

  7. C#基础第七天-作业答案-利用面向对象的思想去实现名片-动态添加

    class Card { private string name; public string Name { get { return name; } set { name = value; } } ...

  8. PHP批量写入数据、批量删除数据

    批量插入可以参考$sql = "insert into data (id,ip,data)  values ";for($i=0;$i<100;$i++){$sqls[]=& ...

  9. Android 高级UI设计笔记20:RecyclerView 的详解之RecyclerView添加Item点击事件

    1. 引言: RecyclerView侧重的是布局的灵活性,虽说可以替代ListView但是连基本的点击事件都没有,这篇文章就来详细讲解如何为RecyclerView的item添加点击事件,顺便复习一 ...

随机推荐

  1. MongoDB 存储引擎和数据模型设计

    标签: MongoDB NoSQL MongoDB 存储引擎和数据模型设计 1. 存储引擎 1.1 存储引擎是什么 1.2 MongoDB中的默认存储引擎 2. 数据模型设计 2.1 内嵌和引用 2. ...

  2. .Net Html如何上传图片到一般应用程序

    用html实现图片上传 后台采用.net其中在这里要借用一个js插件 在这里我会写一个图片上传的一个小Demo,有不全的地方多多包容,和提议, 我把已经写好的demo已经上传到百度云 在这里可以下载 ...

  3. 【无私分享:ASP.NET CORE 项目实战(第十一章)】Asp.net Core 缓存 MemoryCache 和 Redis

    目录索引 [无私分享:ASP.NET CORE 项目实战]目录索引 简介 经过 N 久反复的尝试,翻阅了网上无数的资料,GitHub上下载了十几个源码参考, Memory 和 Redis 终于写出一个 ...

  4. C#开发微信门户及应用(2)--微信消息的处理和应答

    微信应用如火如荼,很多公司都希望搭上信息快车,这个是一个商机,也是一个技术的方向,因此,有空研究下.学习下微信的相关开发,也就成为计划的安排事情之一了.本系列文章希望从一个循序渐进的角度上,全面介绍微 ...

  5. FreeMarker的基础语法

    FreeMarker语言 FreeMarker语言概述 FreeMarker是一个模板引擎,一个基于模板生成文本输出的通用工具,使用纯Java编写. FreeMarker被设计用来生成HTML Web ...

  6. 3.2 js六大数据类型

    js中有六种数据类型,包括五种基本数据类型(Number,String,Boolean,Null,Undefined),和一种混合数据类型(Object). 前面说到js中变量是松散类型的,因此有时候 ...

  7. JDBC数据库访问操作的动态监测 之 Log4JDBC

    log4jdbc是一个JDBC驱动器,能够记录SQL日志和SQL执行时间等信息.log4jdbc使用SLF4J(Simple Logging Facade)作为日志系统. 特性: 1.支持JDBC3和 ...

  8. iOS - 捕获应用程序崩溃日志

    作为一名iOS移动应用开发者,为了确保你的应用程序正确无误,在将应用程序提交到应用商店之前,你必定会进行大量的测试工作:而且在你测试的过程中应用程序运行的很好,但是在应用商店上线之后,还是有用户抱怨应 ...

  9. WebViewJavascriptBridge源码探究--看OC和JS交互过程

    今天把实现OC代码和JS代码交互的第三方库WebViewJavascriptBridge源码看了下,oc调用js方法我们是知道的,系统提供了stringByEvaluatingJavaScriptFr ...

  10. AngularJS 输入验证

    AngularJS 表单和控件可以验证输入的数据. 实例 <!DOCTYPE html> <html> <script src= "http://apps.bd ...