zabbix_add_screen.py 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259
  1. #! /usr/bin/env python
  2. # coding: utf-8
  3. import requests
  4. import json
  5. import pymysql
  6. from pprint import pprint
  7. class zabbixApi(object):
  8. def __init__(self):
  9. self.url = 'http://127.0.0.1:9091/zabbix/api_jsonrpc.php'
  10. self.headers = {'Content-Type': 'application/json'}
  11. auth = {
  12. "jsonrpc": "2.0",
  13. "method": "user.login",
  14. "params": {
  15. "user": "user",
  16. "password":"password"
  17. },
  18. "id": 1,
  19. "auth":None,
  20. }
  21. response = requests.post(self.url, data=json.dumps(auth), headers=self.headers)
  22. self.authid = json.loads(response.text)['result']
  23. conn = pymysql.connect(
  24. host="127.0.0.1",
  25. user="zabbix",
  26. password="openet123",
  27. database="zabbix",
  28. charset="utf8")
  29. self.cursor = conn.cursor()
  30. def from_itemid_to_value(self, itemid):
  31. sql = "select value_avg from trends_uint where itemid=%s order by clock desc limit 1" % itemid
  32. self.cursor.execute(sql)
  33. data = self.cursor.fetchall()
  34. try:
  35. value = data[0][0]
  36. except:
  37. value = 0
  38. return value
  39. def from_graphid_to_itemid(self, graphid):
  40. sql = "select itemid from graphs_items where graphid= %s" % graphid
  41. self.cursor.execute(sql)
  42. ##### tobe continue
  43. data = self.cursor.fetchall()
  44. _in, _out = data
  45. _in = _in[0]
  46. _out = _out[0]
  47. _in_v = self.from_itemid_to_value(_in)
  48. _out_v = self.from_itemid_to_value(_out)
  49. if _in_v > _out_v :
  50. _out_v, _in_v = _in_v, _out_v
  51. return _out_v
  52. def get_hosts(self):
  53. neirong={
  54. "jsonrpc": "2.0",
  55. "method": "host.get",
  56. "params": {
  57. "output": [
  58. "hostid",
  59. "host"
  60. ],
  61. "selectInterfaces": [
  62. "interfaceid",
  63. "ip"
  64. ]
  65. },
  66. "id": 2,
  67. "auth": self.authid
  68. }
  69. response = requests.post(self.url, data=json.dumps(neirong), headers=self.headers)
  70. host_ids = []
  71. for host in response.json()['result']:
  72. host_ids.append(host['hostid'])
  73. return host_ids
  74. def get_conn_value(self):
  75. host_ids = self.get_hosts()
  76. filter_result ={}
  77. for hostid in host_ids:
  78. neirong={
  79. "jsonrpc": "2.0",
  80. "method": "item.get",
  81. "params": {
  82. "output": "extend",
  83. "hostids": hostid,
  84. "search": {
  85. "key_": "conn.all"
  86. },
  87. "sortfield": "name"
  88. },
  89. "auth": self.authid,
  90. "id": 1
  91. }
  92. response = requests.post(self.url, data=json.dumps(neirong), headers=self.headers)
  93. result = response.json()['result']
  94. for item in result:
  95. # if item.get('name') == "conn.all":
  96. # filter_result[item.get("itemid")] = int(item.get("lastvalue"))
  97. filter_result[hostid] = int(item.get("lastvalue"))
  98. return sorted(filter_result.items(), key=lambda item:item[1], reverse=True)
  99. def get_cpu_value(self):
  100. host_ids = self.get_hosts()
  101. filter_result ={}
  102. for hostid in host_ids:
  103. neirong={
  104. "jsonrpc": "2.0",
  105. "method": "item.get",
  106. "params": {
  107. "output": "extend",
  108. "hostids": hostid,
  109. "search": {
  110. "key_": "system.cpu.util[,user]"
  111. },
  112. "sortfield": "name"
  113. },
  114. "auth": self.authid,
  115. "id": 1
  116. }
  117. response = requests.post(self.url, data=json.dumps(neirong), headers=self.headers)
  118. result = response.json()['result']
  119. for item in result:
  120. # if item.get('name') == "conn.all":
  121. # filter_result[item.get("itemid")] = int(item.get("lastvalue"))
  122. filter_result[hostid] = float(item.get("lastvalue"))
  123. return sorted(filter_result.items(), key=lambda item:item[1], reverse=True)
  124. def get_traffic_value(self):
  125. host_ids = self.get_hosts()
  126. filter_result ={}
  127. for hostid in host_ids:
  128. neirong={
  129. "jsonrpc": "2.0",
  130. "method": "item.get",
  131. "params": {
  132. "output": "extend",
  133. "hostids": hostid,
  134. "sortfield": "name"
  135. },
  136. "auth": self.authid,
  137. "id": 1
  138. }
  139. response = requests.post(self.url, data=json.dumps(neirong), headers=self.headers)
  140. result = response.json()['result']
  141. last_value = 0
  142. for item in result:
  143. if "network traffic on" in item['name']:
  144. if int(item.get("lastvalue")) > last_value:
  145. last_value = int(item.get("lastvalue"))
  146. if last_value > 0:
  147. filter_result[hostid] = last_value
  148. return sorted(filter_result.items(), key=lambda item:item[1], reverse=True)
  149. def get_graphid(self, graph_name):
  150. if graph_name == "traffic":
  151. hostid_by_filter = self.get_traffic_value()
  152. if graph_name == "tcp_connection":
  153. hostid_by_filter = self.get_conn_value()
  154. if graph_name == "CPU utilization":
  155. hostid_by_filter = self.get_cpu_value()
  156. host_ids = [host[0] for host in hostid_by_filter]
  157. graph_ids = []
  158. d = {}
  159. for hostid in host_ids:
  160. neirong={
  161. "jsonrpc": "2.0",
  162. "method": "graph.get",
  163. "params": {
  164. "output": "extend",
  165. "hostids": hostid,
  166. "search": {
  167. "key_": "tcp_connection" # does't work.
  168. },
  169. "sortfield": "name"
  170. },
  171. "auth": self.authid,
  172. "id": 1
  173. }
  174. response = requests.post(self.url, data=json.dumps(neirong), headers=self.headers)
  175. for graph in response.json()['result']:
  176. if graph_name in graph['name']:
  177. if "traffic" in graph_name:
  178. v = self.from_graphid_to_itemid(graph['graphid'])
  179. if not d.get('hostid'):
  180. d[hostid] = [v, graph['graphid']]
  181. if v > d[hostid][0]:
  182. d[hostid] = [v, graph['graphid']]
  183. else:
  184. graph_ids.append(graph['graphid'])
  185. if d:
  186. sorted_list = sorted(d.items(), key=lambda item:item[1][0], reverse=True)
  187. for i in sorted_list:
  188. graph_ids.append(i[1][1])
  189. return graph_ids
  190. def create_screen(self, graph_name, screen_name):
  191. screenitems = []
  192. x,y= (0, 0)
  193. for resourceid in self.get_graphid(graph_name):
  194. if not x // 3:
  195. d = {
  196. "resourcetype": 0,
  197. "resourceid": resourceid,
  198. "rowspan": 1,
  199. "colspan": 1,
  200. "x": x,
  201. "y": y
  202. }
  203. x += 1
  204. else:
  205. d = {
  206. "resourcetype": 0,
  207. "resourceid": resourceid,
  208. "rowspan": 1,
  209. "colspan": 1,
  210. "x": x,
  211. "y": y
  212. }
  213. x = 0
  214. y += 1
  215. screenitems.append(d)
  216. if len(screenitems) >= 40:
  217. vsize = 40
  218. screenitems = screenitems[:40]
  219. else:
  220. vsize = len(screenitems)
  221. neirong={
  222. "jsonrpc": "2.0",
  223. "method": "screen.create",
  224. "params": {
  225. "name": screen_name,
  226. "hsize": 4,
  227. "vsize": vsize,
  228. "screenitems": screenitems
  229. },
  230. "auth": self.authid,
  231. "id": 1
  232. }
  233. response = requests.post(self.url, data=json.dumps(neirong), headers=self.headers)
  234. print(response.text)
  235. print("finished.")
  236. if __name__ == '__main__':
  237. # zabbixApi().create_screen("tcp_connection", "TCP_Connections")
  238. # zabbixApi().create_screen("traffic", "Network_Traffic")
  239. zabbixApi().create_screen("CPU utilization", "CPU Usage")