zoukankan      html  css  js  c++  java
  • zabbix auto add and delete screen

    1. #!/usr/bin/env python
    2. #-*-coding:utf-8-*-
    3. # Author : SammyTan
    4. # Email : 729979966@qq.com
    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()
     





  • 相关阅读:
    hnust Snowman
    hnust 可口可乐大促销
    hnust 聚宝盆
    hnust 搬书
    hnust 神奇的序列
    hnust 懒人多动脑
    hnust CZJ-Superman
    集合Set--BST实现
    快速排序
    位运算符
  • 原文地址:https://www.cnblogs.com/gyming/p/5781382.html
Copyright © 2011-2022 走看看