关于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. VS2012程序打包部署详解

    VS2012没有自带打包工具,所以要先下载并安装一个打包工具.我采用微软提供的打包工具:  InstallShield2015LimitedEdition.下载地址:https://msdn.micr ...

  2. 学C#之设计模式系列笔记(1)策略模式

    一.借鉴说明 1.<Head First Design Patterns>(中文名<深入浅出设计模式>) 2.维基百科,策略模式,https://zh.wikipedia.or ...

  3. Oracle同义词

    Oracle的同义词(synonyms)从字面上理解就是别名的意思,和试图的功能类似,就是一种映射关系.本文介绍如何创建同义词语句,删除同义词以及查看同义词语句. Oracle的同义词总结:从字面上理 ...

  4. 浅谈Slick(3)- Slick201:从fp角度了解Slick

    我在上期讨论里已经成功的创建了一个简单的Slick项目,然后又尝试使用了一些最基本的功能.Slick是一个FRM(Functional Relational Mapper),是为fp编程提供的scal ...

  5. 301和302 Http状态有啥区别?

    301和302 Http状态有啥区别? 301,302 都是HTTP状态的编码,都代表着某个URL发生了转移,不同之处在于: 301 redirect: 301 代表永久性转移(Permanently ...

  6. 安装Oracle时出现环境变量Path的值大于1023的解决办法

    出现的情况我就不说了,直接重点: 计算机->属性->高级系统设置->高级->环境变量 1)在"系统变量"编辑Path,全选将其中的路径全部复制出来放到文本文 ...

  7. css单行文本与多行溢出文本的省略号问题

    在文字布局和代码编写过程中遇到文本溢出是常有的事,下面总结一下对于单行文本溢出和多行文本溢出省略号的处理. 一.单行文本省略号 <p class="text1"> 这是 ...

  8. div 模拟<select>事件

    IE7 下,不能够自定义<select>/<option>的样式,所以为了方便起见,用div可以进行模拟 <!doctype html> <html> ...

  9. Oracle研究专题:Oracle系统安装与配置

    最近开始研究Oracle数据库,盖因公司的系统要么Oracle要么是mysql吧. 作为一个IT工作者,没有碰过Oracle是一件很匪夷所思得事情. 想到过去几年,乃至接触IT行业开始就只有玩过sql ...

  10. HTML学习(一)基础篇

    这篇文章有人比我总结的好,适用于新手,我就适当的铺垫一下,结尾处会给你们网站,我就不班门弄斧了. 一)HTML结构 1.<head>标签 <title> <base/&g ...