python批量添加zabbix Screens的两个脚本分享


Posted in Python onJanuary 16, 2017

前言

在最初搭建公司监控系统的时候,最头疼的是需要把同类项目组的相同图形添加到一个Screens,由于只能一个一个的添加,非常耗时耗经历。

下面分享两个脚本来解决这个头疼的问题。

1.将单个主机的所有图形添加到一个Screens

使用方法

#更改main()函数里的url、username、password

#参数一:主机名

#参数二:筛选图名称

python zabbix_screen_host.py 'zabbixserver' 'zabbixserver'

zabbix_screen_host.py脚本内容

#!/usr/bin/env python
#zabbix_screen_host.py
import urllib2
import json
import argparse
def authenticate(url, username, password):
 values = {'jsonrpc': '2.0',
 'method': 'user.login',
 'params': {
  'user': username,
  'password': password
 },
 'id': '0'
 }
 data = json.dumps(values)
 req = urllib2.Request(url, data, {'Content-Type': 'application/json-rpc'})
 response = urllib2.urlopen(req, data)
 output = json.loads(response.read())
 try:
 message = output['result']
 except:
 message = output['error']['data']
 print message
 quit()
 return output['result']
def getGraph(hostname, url, auth, graphtype, dynamic, columns):
 if (graphtype == 0):
 selecttype = ['graphid']
 select = 'selectGraphs'
 if (graphtype == 1):
 selecttype = ['itemid', 'value_type']
 select = 'selectItems'
 values = {'jsonrpc': '2.0',
 'method': 'host.get',
 'params': {
  select: selecttype,
  'output': ['hostid', 'host'],
  'searchByAny': 1,
  'filter': {
  'host': hostname
  }
 },
 'auth': auth,
 'id': '2'
 }
 data = json.dumps(values)
 req = urllib2.Request(url, data, {'Content-Type': 'application/json-rpc'})
 response = urllib2.urlopen(req, data)
 host_get = response.read()
 output = json.loads(host_get)
 # print json.dumps(output)
 graphs = []
 if (graphtype == 0):
 for i in output['result'][0]['graphs']:
 graphs.append(i['graphid'])
 if (graphtype == 1):
 for i in output['result'][0]['items']:
 if int(i['value_type']) in (0, 3):
 graphs.append(i['itemid'])
 graph_list = []
 x = 0
 y = 0
 for graph in graphs:
 graph_list.append({
 "resourcetype": graphtype,
 "resourceid": graph,
 "width": "500",
 "height": "100",
 "x": str(x),
 "y": str(y),
 "colspan": "1",
 "rowspan": "1",
 "elements": "0",
 "valign": "0",
 "halign": "0",
 "style": "0",
 "url": "",
 "dynamic": str(dynamic)
 })
 x += 1
 if x == columns:
 x = 0
 y += 1
 return graph_list
def screenCreate(url, auth, screen_name, graphids, columns):
 # print graphids
 if len(graphids) % columns == 0:
 vsize = len(graphids) / columns
 else:
 vsize = (len(graphids) / columns) + 1
 values = {"jsonrpc": "2.0",
 "method": "screen.create",
 "params": [{
  "name": screen_name,
  "hsize": columns,
  "vsize": vsize,
  "screenitems": []
 }],
 "auth": auth,
 "id": 2
 }
 for i in graphids:
 values['params'][0]['screenitems'].append(i)
 data = json.dumps(values)
 req = urllib2.Request(url, data, {'Content-Type': 'application/json-rpc'})
 response = urllib2.urlopen(req, data)
 host_get = response.read()
 output = json.loads(host_get)
 try:
 message = output['result']
 except:
 message = output['error']['data']
 print json.dumps(message)
 
def main():
 url = 'http://zabbixip/zabbix/api_jsonrpc.php'
 username = "***"
 password = "***"
 parser = argparse.ArgumentParser(description='Create Zabbix screen from all of a host Items or Graphs.')
 parser.add_argument('hostname', metavar='H', type=str,
  help='Zabbix Host to create screen from')
 parser.add_argument('screenname', metavar='N', type=str,
  help='Screen name in Zabbix. Put quotes around it if you want spaces in the name.')
 parser.add_argument('-c', dest='columns', type=int, default=3,
  help='number of columns in the screen (default: 3)')
 parser.add_argument('-d', dest='dynamic', action='store_true',
  help='enable for dynamic screen items (default: disabled)')
 parser.add_argument('-t', dest='screentype', action='store_true',
  help='set to 1 if you want item simple graphs created (default: 0, regular graphs)')
 args = parser.parse_args()
 hostname = args.hostname
 screen_name = args.screenname
 columns = args.columns
 dynamic = (1 if args.dynamic else 0)
 screentype = (1 if args.screentype else 0)
 auth = authenticate(url, username, password)
 graphids = getGraph(hostname, url, auth, screentype, dynamic, columns)
 print "Screen Name: " + screen_name
 print "Total Number of Graphs: " + str(len(graphids))
 screenCreate(url, auth, screen_name, graphids, columns)
if __name__ == '__main__':
 main()

2.将同组主机的同一图形添加到一个Screens

使用方法

#更改main()函数里的url、username、password

#-g :组名称

#-G:图形名称

#-n :筛选(screen)图名称

#-c : 一行有多少图形

python zabbix_screen_group.py -g 'zabbix' -G 'icmp-ping' -n 'zabbix-icmp-ping' -c 2

zabbix_screen_group.py脚本内容

#!/usr/bin/env python
import urllib2
import sys
import json
import argparse
 
#定义通过HTTP方式访问API地址的函数,后面每次请求API的各个方法都会调用这个函数
def requestJson(url,values): 
 data = json.dumps(values)
 req = urllib2.Request(url, data, {'Content-Type': 'application/json-rpc'})
 response = urllib2.urlopen(req, data)
 output = json.loads(response.read())
# print output
 try:
 message = output['result']
 except:
 message = output['error']['data']
 print message
 quit()
 
 return output['result']
 
#API接口认证的函数,登录成功会返回一个Token
def authenticate(url, username, password):
 values = {'jsonrpc': '2.0',
  'method': 'user.login',
  'params': {
   'user': username,
   'password': password
  },
  'id': '0'
  }
 idvalue = requestJson(url,values)
 return idvalue
 
#定义更加主机分组名称获取各个hostid的函数
def getHosts(groupname,url,auth):
 host_list = []
 values = {'jsonrpc': '2.0',
  'method': 'hostgroup.get',
  'params': {
   'output': 'extend',
   'filter': {
   'name': groupname
   },
 
   'selectHosts' : ['hostid','host'],
  },
  'auth': auth,
  'id': '2'
  }
 output = requestJson(url,values)
 for host in output[0]['hosts']:
 host_list.append(host['hostid'])
 return host_list
 
#定义获取graphid的函数
def getGraphs(host_list,name_list, url, auth, columns, graphtype=0 ,dynamic=0):
 if (graphtype == 0):
 selecttype = ['graphid']
 select = 'selectGraphs'
 if (graphtype == 1):
 selecttype = ['itemid', 'value_type']
 select = 'selectItems'
 values=({'jsonrpc' : '2.0',
  'method' : 'graph.get',
  'params' : {
   'output' : ['graphid','name'],
   select : [selecttype,'name'],
   'hostids' : host_list,
   'sortfield' : 'name',
   'filter' : {
    'name' : name_list,
 
    },
   },
  'auth' : auth,
  'id' : 3
  })
 output = requestJson(url,values)
 bb = sorted(output,key = lambda x:x['graphid'])
 graphs = []
 if (graphtype == 0):
 for i in bb:
  print i
  graphs.append(i['graphid'])
 if (graphtype == 1):
 for i in bb:
  if int(i['value_type']) in (0, 3):
  graphs.append(i['itemid'])
 
 graph_list = []
 x = 0
 y = 0
 for graph in graphs:
 print "x is " + str(x)
 print "y is " + str(y)
 graph_list.append({
  "resourcetype": graphtype,
  "resourceid": graph,
  "width": "500",
  "height": "100",
  "x": str(x),
  "y": str(y),
  "colspan": "1",
  "rowspan": "1",
  "elements": "0",
  "valign": "0",
  "halign": "0",
  "style": "0",
  "url": "",
  "dynamic": str(dynamic)
 })
 x += 1
# print type(x)
# print type(columns)
 if x == int(columns):
  x = 0
  y += 1
# print graph_list
 return graph_list
 
#定义创建screen的函数
def screenCreate(url, auth, screen_name, graphids, columns):
 columns = int(columns)
 if len(graphids) % columns == 0:
 vsize = len(graphids) / columns
 else:
 vsize = (len(graphids) / columns) + 1
 
#先使用screen.get判断给定的screen name是否存在
 values0 = {
  "jsonrpc" : "2.0",
  "method" : "screen.get",
  "params" : {
   "output" : "extend",
   "filter" : {
   "name" : screen_name,
    }
    },
  "auth" : auth,
  "id" : 2
  }
 values = {
  "jsonrpc": "2.0",
  "method": "screen.create",
  "params": {
   "name": screen_name,
   "hsize": columns,
   "vsize": vsize,
   "screenitems": []
  },
  "auth": auth,
  "id": 2
  }
 output0 = requestJson(url,values0)
 print output0
 
#如果给定的screen name不存在则直接创建screen 
 if output0 == []:
 print "The Given Screen Name Not Exists"
 print "Creating Screen %s" %screen_name
 for i in graphids:
  values['params']['screenitems'].append(i)
 output = requestJson(url,values)
 else:
 
 
#如果给定的screen name已经存在,直接创建screen是不行的,
#要么先使用screen.delete把原来的screen删除掉,然后再创建,
#要么直接使用screen.update更新原来那个screen,
#使用screen.delete会产生新的screenid,
#使用screen.update比较合理一点。
 print "The Given Screen Name Already Exists"
 update_screenid=output0[0]["screenid"]
 print update_screenid
 print "Updating Screen Name %s Screen ID %s" %(screen_name,update_screenid)
 values1 = {
  "jsonrpc" : "2.0",
  "method" : "screen.update",
  "params" : {
   "screenid" : update_screenid,
   "screenitems": []
    },
  "auth" : auth,
  "id" : 2
   }
 output1 = requestJson(url,values1)
 print output1
 print "Updating Screen Name %s" %screen_name
 for i in graphids:
  values1['params']['screenitems'].append(i)
 output = requestJson(url,values1)
 
def main():
 url = 'http://zabbixip/zabbix/api_jsonrpc.php'
 username = '****'
 password = '****'
 auth = authenticate(url, username, password)
 host_list = getHosts(groupname,url,auth)
 print host_list
 graph_ids = getGraphs(host_list,graphname, url, auth, columns)
 screenCreate(url, auth, screenname, graph_ids, columns)
if __name__ == '__main__':
 parser = argparse.ArgumentParser(description='Create Zabbix screen from all of a host Items or Graphs.')
 parser.add_argument('-G', dest='graphname', nargs='+',metavar=('grah name'),
   help='Zabbix Host Graph to create screen from')
 parser.add_argument('-H', dest='hostname', nargs='+',metavar=('10.19.111.145'),
   help='Zabbix Host to create screen from')
 parser.add_argument('-g', dest='groupname', nargs='+',metavar=('linux server'),
   help='Zabbix Group to create screen from')
 parser.add_argument('-n', dest='screenname', type=str,
   help='Screen name in Zabbix. Put quotes around it if you want spaces in the name.')
 parser.add_argument('-c', dest='columns', type=int,
   help='number of columns in the screen')
 args = parser.parse_args()
 print args
 hostname = args.hostname
 groupname = args.groupname
 screenname = args.screenname
 columns = args.columns
 graphname = args.graphname
 if columns is None:
 columns = len(graphname)
# print columns
 main()

总结

以上就是这篇文章的全部内容了,希望本文的内容的内容对大家的学习或者工作能带来一定的帮助,如果有疑问大家可以留言交流。

Python 相关文章推荐
使用Python下的XSLT API进行web开发的简单教程
Apr 15 Python
Python下rrdtool模块的基本使用方法
Nov 13 Python
Python基于回溯法子集树模板解决找零问题示例
Sep 11 Python
Python使用文件锁实现进程间同步功能【基于fcntl模块】
Oct 16 Python
Python 用Redis简单实现分布式爬虫的方法
Nov 23 Python
Python pyinotify模块实现对文档的实时监控功能方法
Oct 13 Python
django+echart绘制曲线图的方法示例
Nov 26 Python
利用python实现对web服务器的目录探测的方法
Feb 26 Python
python开启debug模式的方法
Jun 27 Python
python中的split()函数和os.path.split()函数使用详解
Dec 21 Python
Python IDLE或shell中切换路径的操作
Mar 09 Python
python爬虫scrapy框架之增量式爬虫的示例代码
Feb 26 Python
python一键升级所有pip package的方法
Jan 16 #Python
centos6.7安装python2.7.11的具体方法
Jan 16 #Python
python subprocess 杀掉全部派生的子进程方法
Jan 16 #Python
用python记录运行pid,并在需要时kill掉它们的实例
Jan 16 #Python
python 根据pid杀死相应进程的方法
Jan 16 #Python
总结python实现父类调用两种方法的不同
Jan 15 #Python
利用python程序帮大家清理windows垃圾
Jan 15 #Python
You might like
php模拟asp中的XmlHttpRequest实现http请求的代码
2011/03/24 PHP
php中删除字符串中最先出现某个字符的实现代码
2013/02/03 PHP
destoon实现调用热门关键字的方法
2014/07/15 PHP
PHP实现找出有序数组中绝对值最小的数算法分析
2017/08/07 PHP
使用laravel的migrate创建数据表的方法
2019/09/30 PHP
laravel框架中表单请求类型和CSRF防护实例分析
2019/11/23 PHP
借用Google的Javascript API Loader来加速你的网站
2009/01/28 Javascript
js 验证身份证信息有效性
2014/03/28 Javascript
解决ueditor jquery javascript 取值问题
2014/12/30 Javascript
基于JavaScript FileReader上传图片显示本地链接
2016/05/27 Javascript
easyui中combotree循环获取父节点至根节点并输出路径实现方法
2016/11/10 Javascript
Javascript实现购物车功能的详细代码
2018/05/08 Javascript
vue组件从开发到发布的实现步骤
2018/11/11 Javascript
vux-scroller实现移动端上拉加载功能过程解析
2019/10/08 Javascript
layui实现数据表格自定义数据项
2019/10/26 Javascript
vue 解决uglifyjs-webpack-plugin打包出现报错的问题
2020/08/04 Javascript
解析Mac OS下部署Pyhton的Django框架项目的过程
2016/05/03 Python
Flask框架的学习指南之制作简单blog系统
2016/11/20 Python
简单谈谈Python流程控制语句
2016/12/04 Python
轻量级的Web框架Flask 中模块化应用的实现
2017/09/11 Python
利用python将图片转换成excel文档格式
2017/12/30 Python
Python3转换html到pdf的不同解决方案
2019/03/11 Python
python取余运算符知识点详解
2019/06/27 Python
python数据预处理之数据标准化的几种处理方式
2019/07/17 Python
python实现图像拼接
2020/03/05 Python
解决Pytorch自定义层出现多Variable共享内存错误问题
2020/06/28 Python
Python安装第三方库攻略(pip和Anaconda)
2020/10/15 Python
python如何获得list或numpy数组中最大元素对应的索引
2020/11/16 Python
Python urlopen()参数代码示例解析
2020/12/10 Python
matplotlib实现数据实时刷新的示例代码
2021/01/05 Python
亚洲最大旅游体验平台:KKday
2017/10/21 全球购物
在C语言中实现抽象数据类型什么方法最好
2014/06/26 面试题
年终奖发放方案
2014/06/02 职场文书
博士生专家推荐信
2014/09/26 职场文书
Python基础之元编程知识总结
2021/05/23 Python
纯html+css实现打字效果
2021/08/02 HTML / CSS