zabbix auto add and delete screen

  1. #!/usr/bin/env python
  2. #-*-coding:utf-8-*-
  3. # Author : SammyTan
  4. # Email : [email protected]
  5. # Last modified : 2016-04-25 16:24
  6. # Filename : zabbix_screens_automation.py
  7. # Description : Auto add delete and update zabbix screens
  8. import os
  9. import urllib2
  10. import json
  11. import argparse
  12. url=‘http://10.1.180.166/zabbix/api_jsonrpc.php‘
  13. username=‘Admin‘
  14. password=‘zabbix‘
  15. def authenticate(url, username, password):
  16. values ={‘jsonrpc‘:‘2.0‘,
  17. ‘method‘:‘user.login‘,
  18. ‘params‘:{
  19. ‘user‘: username,
  20. ‘password‘: password
  21. },
  22. ‘id‘:‘0‘
  23. }
  24. data = json.dumps(values)
  25. req = urllib2.Request(url, data,{‘Content-Type‘:‘application/json-rpc‘})
  26. response = urllib2.urlopen(req, data)
  27. output = json.loads(response.read())
  28. try:
  29. message = output[‘result‘]
  30. except:
  31. message = output[‘error‘][‘data‘]
  32. print message
  33. quit()
  34. return output[‘result‘]
  35. def getHost():
  36. values ={
  37. "jsonrpc":"2.0",
  38. "method":"host.get",
  39. "params":{
  40. "output":[
  41. "host"
  42. ]
  43. },
  44. "id":1,
  45. "auth":"2e92f0d30d878442533da77c15ae7cdd"
  46. }
  47. data = json.dumps(values)
  48. req = urllib2.Request(url, data,{‘Content-Type‘:‘application/json-rpc‘})
  49. response = urllib2.urlopen(req, data)
  50. output = json.loads(response.read())
  51. return output
  52. def getGraph(hostid):
  53. values ={
  54. "jsonrpc":"2.0",
  55. "method":"graph.get",
  56. "params":{
  57. "output":[
  58. "graphid"
  59. ],
  60. "hostids": hostid
  61. },
  62. "auth":"2e92f0d30d878442533da77c15ae7cdd",
  63. "id":1
  64. }
  65. data = json.dumps(values)
  66. req = urllib2.Request(url, data,{‘Content-Type‘:‘application/json-rpc‘})
  67. response = urllib2.urlopen(req, data)
  68. host_get = response.read()
  69. output = json.loads(host_get)
  70. #print json.dumps(output)
  71. return output
  72. def getScreentimeid(screenid):
  73. values ={
  74. "jsonrpc":"2.0",
  75. "method":"screen.get",
  76. "params":{
  77. "output":"extend",
  78. "selectScreenItems":[
  79. "screenitemid"
  80. ],
  81. "screenids": screenid
  82. },
  83. "auth":"2e92f0d30d878442533da77c15ae7cdd",
  84. "id":1
  85. }
  86. data = json.dumps(values)
  87. req = urllib2.Request(url, data,{‘Content-Type‘:‘application/json-rpc‘})
  88. response = urllib2.urlopen(req, data)
  89. host_get = response.read()
  90. output = json.loads(host_get)
  91. #print json.dumps(output)
  92. return output
  93. def getScreen():
  94. values ={
  95. "jsonrpc":"2.0",
  96. "method":"screen.get",
  97. "params":{
  98. "output":[
  99. "name",
  100. "screenid"
  101. ]
  102. },
  103. "auth":"2e92f0d30d878442533da77c15ae7cdd",
  104. "id":1
  105. }
  106. data = json.dumps(values)
  107. req = urllib2.Request(url, data,{‘Content-Type‘:‘application/json-rpc‘})
  108. response = urllib2.urlopen(req, data)
  109. host_get = response.read()
  110. output = json.loads(host_get)
  111. return output
  112. def screenDelete(screenid):
  113. values ={
  114. "jsonrpc":"2.0",
  115. "method":"screen.delete",
  116. "params":[
  117. screenid
  118. ],
  119. "auth":"2e92f0d30d878442533da77c15ae7cdd",
  120. "id":1
  121. }
  122. data = json.dumps(values)
  123. req = urllib2.Request(url, data,{‘Content-Type‘:‘application/json-rpc‘})
  124. response = urllib2.urlopen(req, data)
  125. host_get = response.read()
  126. output = json.loads(host_get)
  127. return output
  128. #os.system(‘python /root/Scripts_Tmemplate/Auto_add_screens.py -c 2 $each_host $each_host‘)
  129. def main():
  130. host_output=getHost()
  131. host_list =[]
  132. # add host to host list
  133. for host in host_output[‘result‘]:
  134. #print host
  135. host_list.append(host[‘host‘])
  136. screenname_list =[]
  137. screen_output=getScreen()
  138. # add screen name to saceen list
  139. for name in screen_output[‘result‘]:
  140. screenname_list.append(name[‘name‘])
  141. #Check host , if this host not have screen ,the self create screen .
  142. for host in host_list:
  143. if host notin screenname_list:# if this host not in screen list , the creend the host screen
  144. os.system(‘python /root/Scripts_Tmemplate/Auto_add_screens.py -c 2 %s %s‘%(host,host))  
  145. #### 该脚本在下面
  146. print‘Create %s host screen‘%(host)
  147. #Delete invalid screen
  148. for name in screenname_list:
  149. for sid in screen_output[‘result‘]:
  150. if name in sid[‘name‘]:
  151. screenid = sid[‘screenid‘]
  152. if name notin host_list:
  153. delete_result = screenDelete(screenid)
  154. print‘Delete %s host screen‘%(name)
  155. #Check host graphs number, if graphs number grant than exsit screens graphs , the delete it after recreated.
  156. for screenid in screen_output[‘result‘]:
  157. #print screenid
  158. screenGraphs = getScreentimeid(screenid[‘screenid‘])
  159. for sid in screenGraphs[‘result‘]:
  160. for host in host_output[‘result‘]:
  161. if host[‘host‘]in screenid[‘name‘]:
  162. hostid = host[‘hostid‘]
  163. hostname = host[‘host‘]
  164. hostGraphs = getGraph(hostid)
  165. #print host[‘host‘],len(hostGraphs[‘result‘]),len(sid[‘screenitems‘])
  166. if len(hostGraphs[‘result‘])> len(sid[‘screenitems‘]):
  167. delete_result = screenDelete(host[‘hostid‘])
  168. os.system(‘python /root/Scripts_Tmemplate/Auto_add_screens.py -c 2 %s %s‘%(hostname,hostname))
  169. print‘Update %s host screen‘%(hostname)
  170. else:
  171. print‘All screen already sync .‘
  172. if __name__ ==‘__main__‘:
  173. main()
  1. #!/usr/bin/env python
  2. import urllib2
  3. import json
  4. import argparse
  5. def authenticate(url, username, password):
  6. values ={‘jsonrpc‘:‘2.0‘,
  7. ‘method‘:‘user.login‘,
  8. ‘params‘:{
  9. ‘user‘: username,
  10. ‘password‘: password
  11. },
  12. ‘id‘:‘0‘
  13. }
  14. data = json.dumps(values)
  15. req = urllib2.Request(url, data,{‘Content-Type‘:‘application/json-rpc‘})
  16. response = urllib2.urlopen(req, data)
  17. output = json.loads(response.read())
  18. try:
  19. message = output[‘result‘]
  20. except:
  21. message = output[‘error‘][‘data‘]
  22. print message
  23. quit()
  24. return output[‘result‘]
  25. def getGraph(hostname, url, auth, graphtype, dynamic, columns):
  26. if(graphtype ==0):
  27. selecttype =[‘graphid‘]
  28. select =‘selectGraphs‘
  29. if(graphtype ==1):
  30. selecttype =[‘itemid‘,‘value_type‘]
  31. select =‘selectItems‘
  32. values ={‘jsonrpc‘:‘2.0‘,
  33. ‘method‘:‘host.get‘,
  34. ‘params‘:{
  35. select: selecttype,
  36. ‘output‘:[‘hostid‘,‘host‘],
  37. ‘searchByAny‘:1,
  38. ‘filter‘:{
  39. ‘host‘: hostname
  40. }
  41. },
  42. ‘auth‘: auth,
  43. ‘id‘:‘2‘
  44. }
  45. data = json.dumps(values)
  46. req = urllib2.Request(url, data,{‘Content-Type‘:‘application/json-rpc‘})
  47. response = urllib2.urlopen(req, data)
  48. host_get = response.read()
  49. output = json.loads(host_get)
  50. # print json.dumps(output)
  51. graphs =[]
  52. if(graphtype ==0):
  53. for i in output[‘result‘][0][‘graphs‘]:
  54. graphs.append(i[‘graphid‘])
  55. if(graphtype ==1):
  56. for i in output[‘result‘][0][‘items‘]:
  57. if int(i[‘value_type‘])in(0,3):
  58. graphs.append(i[‘itemid‘])
  59. graph_list =[]
  60. x =0
  61. y =0
  62. for graph in graphs:
  63. graph_list.append({
  64. "resourcetype": graphtype,
  65. "resourceid": graph,
  66. "width":"500",
  67. "height":"200",
  68. "x": str(x),
  69. "y": str(y),
  70. "colspan":"1",
  71. "rowspan":"1",
  72. "elements":"0",
  73. "valign":"0",
  74. "halign":"0",
  75. "style":"0",
  76. "url":"",
  77. "dynamic": str(dynamic)
  78. })
  79. x +=1
  80. if x == columns:
  81. x =0
  82. y +=1
  83. return graph_list
  84. def screenCreate(url, auth, screen_name, graphids, columns):
  85. # print graphids
  86. if len(graphids)% columns ==0:
  87. vsize = len(graphids)/ columns
  88. else:
  89. vsize =(len(graphids)/ columns)+1
  90. values ={"jsonrpc":"2.0",
  91. "method":"screen.create",
  92. "params":[{
  93. "name": screen_name,
  94. "hsize": columns,
  95. "vsize": vsize,
  96. "screenitems":[]
  97. }],
  98. "auth": auth,
  99. "id":2
  100. }
  101. for i in graphids:
  102. values[‘params‘][0][‘screenitems‘].append(i)
  103. data = json.dumps(values)
  104. req = urllib2.Request(url, data,{‘Content-Type‘:‘application/json-rpc‘})
  105. response = urllib2.urlopen(req, data)
  106. host_get = response.read()
  107. output = json.loads(host_get)
  108. try:
  109. message = output[‘result‘]
  110. except:
  111. message = output[‘error‘][‘data‘]
  112. print json.dumps(message)
  113. def main():
  114. url =‘http://10.1.180.166/zabbix/api_jsonrpc.php‘
  115. username ="Admin"
  116. password ="zabbix"
  117. parser = argparse.ArgumentParser(description=‘Create Zabbix screen from all of a host Items or Graphs.‘)
  118. parser.add_argument(‘hostname‘, metavar=‘H‘, type=str,
  119. help=‘Zabbix Host to create screen from‘)
  120. parser.add_argument(‘screenname‘, metavar=‘N‘, type=str,
  121. help=‘Screen name in Zabbix. Put quotes around it if you want spaces in the name.‘)
  122. parser.add_argument(‘-c‘, dest=‘columns‘, type=int, default=2,
  123. help=‘number of columns in the screen (default: 2)‘)
  124. parser.add_argument(‘-d‘, dest=‘dynamic‘, action=‘store_true‘,
  125. help=‘enable for dynamic screen items (default: disabled)‘)
  126. parser.add_argument(‘-t‘, dest=‘screentype‘, action=‘store_true‘,
  127. help=‘set to 1 if you want item simple graphs created (default: 0, regular graphs)‘)
  128. args = parser.parse_args()
  129. hostname = args.hostname
  130. screen_name = args.screenname
  131. columns = args.columns
  132. dynamic =(1if args.dynamic else0)
  133. screentype =(1if args.screentype else0)
  134. auth = authenticate(url, username, password)
  135. graphids = getGraph(hostname, url, auth, screentype, dynamic, columns)
  136. print"Screen Name: "+ screen_name
  137. print"Total Number of Graphs: "+ str(len(graphids))
  138. screenCreate(url, auth, screen_name, graphids, columns)
  139. if __name__ ==‘__main__‘:
  140. main()

来自为知笔记(Wiz)

时间: 2024-10-06 00:23:20

zabbix auto add and delete screen的相关文章

zabbix auto registration

1./etc/zabbix/zabbix_agent.conf serverActive=zabbix server ip 2.frontend configuration>actions>even resource:auto registration>create action name: auto registration operations>operations: Send message to user groups: Zabbix administrators via

Select,Add,Update,Delete

//查询 public static DataSet select(string tableName,string whereStr) { string sql = "select * from "+tableName+whereStr; try { return DbHelp.ExecSql(sql); } catch (Exception e1) { return null; } } //删除单条 public static int delete (string tableName

ThinkPHP add save delete的返回说明

如果你的主键是自增类型的话,add方法的返回值就是该主键的值.不是自增主键的话,返回值表示插入数据的个数.如果返回false则表示写入出错. save方法的返回值是影响的记录数,如果返回false则表示更新出错,返回值如果为0表示没有更新. delete方法的返回值是删除的记录数,如果返回值是false则表示SQL出错,返回值如果为0表示没有删除任何数据.

Ubuntu 添加删除用户 How to Add and Delete Users on Ubuntu 16.04

Introduction One of the most basic tasks that you should know how to do on a fresh Linux server is add and remove users. When you create a new system, you are often (such as on DigitalOcean Droplets) only given the root account by default. While runn

[PWA] Add web app to your Home Screen

Clone: Link Modify the structure: Move css, js, image, index.html to an 'app' folder. manifest.json: { "name": "Fireworks App", "short_name": "Fireworks", "icons": [ { "src":"images/firework

zabbix监控系统的介绍及zabbix监控系统的高级应用

监控系统:zabbix 数据的采集->存储->报警(告警)->展示 监控对象:包括主机,主机之间的数据流量 主机:硬件设备 系统指标:CPU,memory io(disk磁盘io network网络io) cpu:sys(系统空间的比例),usr(用户空间的比例) idle 业务指标: SNMP:简单网络管理协议 实现网络管理 jmx:java管理平台 tps:每秒的事务数 qps:每秒的查询书 采集: 多保留趋势数据,历史数据只保留最近几个月的时间 存储: 关系型数据库 rrd轮询存储

居然还有这样使用的auto

今天学习了一下keyword,无意中发现了自己一直未曾接触到的auto 好吧,我又开始胡扯了! automatic storage duration. (deprecated) 1) When declaring variables in block scope, in namespace scope, in init statements of for loops, etc, the type of the variable may be omitted and the keyword aut

Maste Note for OCR / Vote disk Maintenance Operations (ADD/REMOVE/REPLACE/MOVE)

Doc ID 428681.1 Applies to: Oracle Database - Enterprise Edition - Version 10.2.0.1 to 11.2.0.1.0 [Release 10.2 to 11.2]Information in this document applies to any platform. Goal The goal of this note is to provide steps to add, remove, replace or mo

delete分析 引用于 http://www.cnblogs.com/yuzhongwusan/archive/2012/06/14/2549879.html

最近重新温习JS,对delete操作符一直处于一知半解的状态,偶然发现一篇文章,对此作了非常细致深入的解释,看完有茅塞顿开的感觉,不敢独享,大致翻译如下. 原文地址:http://perfectionkills.com/understanding-delete/ P.S. 作者是PrototypeJS的开发组成员之一 ========分割线======== 在开始之前,先让我们看一段代码 Js代码     >>> var sum = function(a, b) {return a +