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实现系统状态监测和故障转移实例方法
Nov 18 Python
python新手经常遇到的17个错误分析
Jul 30 Python
使用python调用zxing库生成二维码图片详解
Jan 10 Python
python根据unicode判断语言类型实例代码
Jan 17 Python
Python获取CPU、内存使用率以及网络使用状态代码
Feb 08 Python
Python中跳台阶、变态跳台阶与矩形覆盖问题的解决方法
May 19 Python
flask框架中勾子函数的使用详解
Aug 01 Python
使用Python求解带约束的最优化问题详解
Feb 11 Python
python实现word文档批量转成自定义格式的excel文档的思路及实例代码
Feb 21 Python
python源文件的字符编码知识点详解
Mar 04 Python
Python实现提取PDF简历信息并存入Excel
Apr 02 Python
基于Python实现射击小游戏的制作
Apr 06 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
表单的一些基本用法与技巧
2006/07/15 Javascript
为开发者准备的10款最好的jQuery日历插件
2014/02/04 Javascript
JS实现鼠标单击与双击事件共存
2014/03/08 Javascript
JavaScript页面模板库handlebars的简单用法
2015/03/02 Javascript
简介JavaScript中用于处理正切的Math.tan()方法
2015/06/15 Javascript
jQuery Mobile中的button按钮组件基础使用教程
2016/05/23 Javascript
AngularJS中table表格基本操作示例
2017/10/10 Javascript
Vue 2.0入门基础知识之内部指令详解
2017/10/15 Javascript
动态加载权限管理模块中的Vue组件
2018/01/16 Javascript
使用Vue自定义指令实现Select组件
2018/05/24 Javascript
简述JS控制台的使用
2018/07/15 Javascript
vue cli 3.0 搭建项目的图文教程
2019/05/17 Javascript
非常实用的jQuery代码段集锦【检测浏览器、滚动、复制、淡入淡出等】
2019/08/08 jQuery
详解vue中v-bind:style效果的自定义指令
2020/01/21 Javascript
vue-cli脚手架的.babelrc文件用法说明
2020/09/11 Javascript
JavaScript 中判断变量是否为数字的示例代码
2020/10/22 Javascript
解决Python2.7读写文件中的中文乱码问题
2018/04/12 Python
基于python神经卷积网络的人脸识别
2018/05/24 Python
Python中if elif else及缩进的使用简述
2018/05/31 Python
Python多线程原理与用法详解
2018/08/20 Python
Python 从相对路径下import的方法
2018/12/04 Python
基于wxPython的GUI实现输入对话框(1)
2019/02/27 Python
python实现银联支付和支付宝支付接入
2019/05/07 Python
将Pytorch模型从CPU转换成GPU的实现方法
2019/08/19 Python
Ubuntu16.04安装python3.6.5步骤详解
2020/01/10 Python
浅谈python出错时traceback的解读
2020/07/15 Python
Windows和Linux动态库应用异同
2016/07/28 面试题
资料员的岗位职责
2013/11/20 职场文书
《乌塔》教学反思
2014/02/17 职场文书
公司开业庆典策划方案
2014/06/04 职场文书
致百米运动员广播稿5篇
2014/10/13 职场文书
面试感谢信范文
2015/01/22 职场文书
工程技术员岗位职责
2015/04/11 职场文书
导游词之太湖
2019/10/08 职场文书
react antd实现动态增减表单
2021/06/03 Javascript
MySQL高速缓存启动方法及参数详解(query_cache_size)
2021/07/01 MySQL