123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259 |
- #! /usr/bin/env python
- # coding: utf-8
- import requests
- import json
- import pymysql
- from pprint import pprint
- class zabbixApi(object):
- def __init__(self):
- self.url = 'http://127.0.0.1:9091/zabbix/api_jsonrpc.php'
- self.headers = {'Content-Type': 'application/json'}
- auth = {
- "jsonrpc": "2.0",
- "method": "user.login",
- "params": {
- "user": "user",
- "password":"password"
- },
- "id": 1,
- "auth":None,
- }
- response = requests.post(self.url, data=json.dumps(auth), headers=self.headers)
- self.authid = json.loads(response.text)['result']
- conn = pymysql.connect(
- host="127.0.0.1",
- user="zabbix",
- password="openet123",
- database="zabbix",
- charset="utf8")
- self.cursor = conn.cursor()
-
- def from_itemid_to_value(self, itemid):
- sql = "select value_avg from trends_uint where itemid=%s order by clock desc limit 1" % itemid
- self.cursor.execute(sql)
- data = self.cursor.fetchall()
- try:
- value = data[0][0]
- except:
- value = 0
- return value
-
- def from_graphid_to_itemid(self, graphid):
- sql = "select itemid from graphs_items where graphid= %s" % graphid
- self.cursor.execute(sql)
- ##### tobe continue
- data = self.cursor.fetchall()
- _in, _out = data
- _in = _in[0]
- _out = _out[0]
- _in_v = self.from_itemid_to_value(_in)
- _out_v = self.from_itemid_to_value(_out)
- if _in_v > _out_v :
- _out_v, _in_v = _in_v, _out_v
- return _out_v
-
-
- def get_hosts(self):
- neirong={
- "jsonrpc": "2.0",
- "method": "host.get",
- "params": {
- "output": [
- "hostid",
- "host"
- ],
- "selectInterfaces": [
- "interfaceid",
- "ip"
- ]
- },
- "id": 2,
- "auth": self.authid
- }
- response = requests.post(self.url, data=json.dumps(neirong), headers=self.headers)
- host_ids = []
- for host in response.json()['result']:
- host_ids.append(host['hostid'])
- return host_ids
-
- def get_conn_value(self):
- host_ids = self.get_hosts()
- filter_result ={}
- for hostid in host_ids:
- neirong={
- "jsonrpc": "2.0",
- "method": "item.get",
- "params": {
- "output": "extend",
- "hostids": hostid,
- "search": {
- "key_": "conn.all"
- },
- "sortfield": "name"
- },
- "auth": self.authid,
- "id": 1
- }
- response = requests.post(self.url, data=json.dumps(neirong), headers=self.headers)
- result = response.json()['result']
- for item in result:
- # if item.get('name') == "conn.all":
- # filter_result[item.get("itemid")] = int(item.get("lastvalue"))
- filter_result[hostid] = int(item.get("lastvalue"))
- return sorted(filter_result.items(), key=lambda item:item[1], reverse=True)
- def get_cpu_value(self):
- host_ids = self.get_hosts()
- filter_result ={}
- for hostid in host_ids:
- neirong={
- "jsonrpc": "2.0",
- "method": "item.get",
- "params": {
- "output": "extend",
- "hostids": hostid,
- "search": {
- "key_": "system.cpu.util[,user]"
- },
- "sortfield": "name"
- },
- "auth": self.authid,
- "id": 1
- }
- response = requests.post(self.url, data=json.dumps(neirong), headers=self.headers)
- result = response.json()['result']
- for item in result:
- # if item.get('name') == "conn.all":
- # filter_result[item.get("itemid")] = int(item.get("lastvalue"))
- filter_result[hostid] = float(item.get("lastvalue"))
- return sorted(filter_result.items(), key=lambda item:item[1], reverse=True)
- def get_traffic_value(self):
- host_ids = self.get_hosts()
- filter_result ={}
- for hostid in host_ids:
- neirong={
- "jsonrpc": "2.0",
- "method": "item.get",
- "params": {
- "output": "extend",
- "hostids": hostid,
- "sortfield": "name"
- },
- "auth": self.authid,
- "id": 1
- }
- response = requests.post(self.url, data=json.dumps(neirong), headers=self.headers)
- result = response.json()['result']
- last_value = 0
- for item in result:
- if "network traffic on" in item['name']:
- if int(item.get("lastvalue")) > last_value:
- last_value = int(item.get("lastvalue"))
- if last_value > 0:
- filter_result[hostid] = last_value
- return sorted(filter_result.items(), key=lambda item:item[1], reverse=True)
-
-
- def get_graphid(self, graph_name):
- if graph_name == "traffic":
- hostid_by_filter = self.get_traffic_value()
- if graph_name == "tcp_connection":
- hostid_by_filter = self.get_conn_value()
- if graph_name == "CPU utilization":
- hostid_by_filter = self.get_cpu_value()
- host_ids = [host[0] for host in hostid_by_filter]
- graph_ids = []
- d = {}
- for hostid in host_ids:
- neirong={
- "jsonrpc": "2.0",
- "method": "graph.get",
- "params": {
- "output": "extend",
- "hostids": hostid,
- "search": {
- "key_": "tcp_connection" # does't work.
- },
- "sortfield": "name"
- },
- "auth": self.authid,
- "id": 1
- }
- response = requests.post(self.url, data=json.dumps(neirong), headers=self.headers)
- for graph in response.json()['result']:
- if graph_name in graph['name']:
- if "traffic" in graph_name:
- v = self.from_graphid_to_itemid(graph['graphid'])
- if not d.get('hostid'):
- d[hostid] = [v, graph['graphid']]
- if v > d[hostid][0]:
- d[hostid] = [v, graph['graphid']]
- else:
- graph_ids.append(graph['graphid'])
- if d:
- sorted_list = sorted(d.items(), key=lambda item:item[1][0], reverse=True)
- for i in sorted_list:
- graph_ids.append(i[1][1])
- return graph_ids
- def create_screen(self, graph_name, screen_name):
- screenitems = []
- x,y= (0, 0)
- for resourceid in self.get_graphid(graph_name):
- if not x // 3:
- d = {
- "resourcetype": 0,
- "resourceid": resourceid,
- "rowspan": 1,
- "colspan": 1,
- "x": x,
- "y": y
- }
- x += 1
- else:
- d = {
- "resourcetype": 0,
- "resourceid": resourceid,
- "rowspan": 1,
- "colspan": 1,
- "x": x,
- "y": y
- }
- x = 0
- y += 1
- screenitems.append(d)
- if len(screenitems) >= 40:
- vsize = 40
- screenitems = screenitems[:40]
- else:
- vsize = len(screenitems)
- neirong={
- "jsonrpc": "2.0",
- "method": "screen.create",
- "params": {
- "name": screen_name,
- "hsize": 4,
- "vsize": vsize,
- "screenitems": screenitems
- },
- "auth": self.authid,
- "id": 1
- }
- response = requests.post(self.url, data=json.dumps(neirong), headers=self.headers)
- print(response.text)
- print("finished.")
- if __name__ == '__main__':
- # zabbixApi().create_screen("tcp_connection", "TCP_Connections")
- # zabbixApi().create_screen("traffic", "Network_Traffic")
- zabbixApi().create_screen("CPU utilization", "CPU Usage")
|