技術(shù)員聯(lián)盟提供win764位系統(tǒng)下載,win10,win7,xp,裝機純凈版,64位旗艦版,綠色軟件,免費軟件下載基地!

當(dāng)前位置:主頁 > 教程 > 服務(wù)器類 >

Zabbix與RRDtool繪圖篇之用ZabbixAPI取監(jiān)控數(shù)據(jù)

來源:技術(shù)員聯(lián)盟┆發(fā)布時間:2018-05-13 00:28┆點擊:

  一起來看一個Zabbix與RRDtool繪圖篇之用ZabbixAPI取監(jiān)控數(shù)據(jù)技巧文章,希望下文可以幫助到各位。

  經(jīng)過一個星期的死磕,Zabbix取數(shù)據(jù)和RRDtool繪圖都弄清楚了,做第一運維平臺的時候繪圖取數(shù)據(jù)是直接從Zabbix的數(shù)據(jù)庫取的,顯得有點笨拙,不過借此也了解了Zabbix數(shù)據(jù)庫結(jié)構(gòu)還是有不少的收獲。

  學(xué)習(xí)Zabbix的API官方文檔少不了,官方文檔地址鏈接https://www.zabbix.com/documentation/ 大家選擇對應(yīng)的版本就好了,不過2.0版本的API手冊位置有點特別開始我還以為沒有,后來找到了如下https://www.zabbix.com/documentation/2.0/manual/appendix/api/api 用ZabbixAPI取監(jiān)控數(shù)據(jù)的思路大致是這樣的,先獲取所有監(jiān)控的主機,再遍歷每臺主機獲取每臺主機的所有圖形,最后獲取每張圖形每個監(jiān)控對象(item)的最新的監(jiān)控數(shù)據(jù)或者一定時間范圍的數(shù)據(jù)。 下面按照上面的思路就一段一段的貼出我的程序代碼:

  1、登錄Zabbix獲取通信token

  #!/usr/bin/env python

  #coding=utf-8

  import json

  import urllib2

  import sys

  ##########################

  class Zabbix:

  def __init__(self):

  self.url = ":xxxxx/api_jsonrpc.php"

  self.header = {"Content-Type": "application/json"}

  self.authID = self.user_login()

  def user_login(self):

  data = json.dumps({

  "jsonrpc": "2.0",

  "method": "user.login",

  "params": {"user": "用戶名", "password": "密碼"},

  "id": 0})

  request = urllib2.Request(self.url,data)

  for key in self.header:

  request.add_header(key,self.header[key])

  try:

  result = urllib2.urlopen(request)

  except URLError as e:

  print "Auth Failed, Please Check Your Name And Password:",e.code

  else:

  response = json.loads(result.read())

  result.close()

  authID = response['result']

  return authID

  ##################通用請求處理函數(shù)####################

  def get_data(self,data,hostip=""):

  request = urllib2.Request(self.url,data)

  for key in self.header:

  request.add_header(key,self.header[key])

  try:

  result = urllib2.urlopen(request)

  except URLError as e:

  if hasattr(e, 'reason'):

  print 'We failed to reach a server.'

  print 'Reason: ', e.reason

  elif hasattr(e, 'code'):

  print 'The server could not fulfill the request.'

  print 'Error code: ', e.code

  return 0

  else:

  response = json.loads(result.read())

  result.close()

  return response

  2、獲取所有主機

  #####################################################################

  #獲取所有主機和對應(yīng)的hostid

  def hostsid_get(self):

  data = json.dumps({

  "jsonrpc": "2.0",

  "method": "host.get",

  "params": { "output":["hostid","status","host"]},

  "auth": self.authID,

  "id": 1})

  res = self.get_data(data)['result']

  #可以返回完整信息

  #return res

  hostsid = []

  if (res != 0) and (len(res) != 0):

  for host in res:

  if host['status'] == '1':

  hostsid.append({host['host']:host['hostid']})

  elif host['status'] == '0':

  hostsid.append({host['host']:host['hostid']})

  else:

  pass

  return hostsid

  返回的結(jié)果是一個列表,每個元素是一個字典,字典的key代表主機名,value代表hostid

Zabbix與RRDtool繪圖篇之用ZabbixAPI取監(jiān)控數(shù)據(jù) 三聯(lián)

  3、獲取每臺主機的每張圖形

  ###################################################################

  #查找一臺主機的所有圖形和圖形id

  def hostgraph_get(self, hostname):

  data = json.dumps({

  "jsonrpc": "2.0",

  "method": "host.get",

  "params": { "selectGraphs": ["graphid","name"],

  "filter": {"host": hostname}},

  "auth": self.authID,

  "id": 1})

  res = self.get_data(data)['result']

  #可以返回完整信息rs,含有hostid

  return res[0]['graphs']

  注意傳入的參數(shù)是主機名而不是主機id,結(jié)果也是由字典組成的列表。

zabbixget02

  4、獲取每張圖的監(jiān)控對象item

  #可以返回完整信息rs,含有hostid

  tmp = res[0]['items']

  items = []

  for value in tmp:

  if '$' in value['name']:

  name0 = value['key_'].split('[')[1].split(']')[0].replace(',', '')

  name1 = value['name'].split()

  if 'CPU' in name1:

  name1.pop(-2)

  name1.insert(1,name0)

  else:

  name1.pop()

  name1.append(name0)

  name = ' '.join(name1)

  tmpitems = {'itemid':value['itemid'],'delay':value['delay'],'units':value['units'],'name':name,'value_type':value['value_type'],

'lastclock':value['lastclock'],'lastvalue':value['lastvalue']}

  else:

  tmpitems = {'itemid':value['itemid'],'delay':value['delay'],'units':value['units'],'name':value['name'],'value_type':value['value_type'],

'lastclock':value['lastclock'],'lastvalue':value['lastvalue']}

  items.append(tmpitems)

  return items