技术员联盟提供win764位系统下载,win10,win7,xp,装机纯净版,64位旗舰版,绿色软件,免费软件下载基地!

当前位置:主页 > 教程 > 服务器类 >

Zabbix与RRDtool绘图篇之用ZabbixAPI取监控数据

来源:技术员联盟┆发布时间:2018-05-13 00:28┆点击:

  一起来看一个Zabbix与RRDtool绘图篇之用ZabbixAPI取监控数据技巧文章,希望下文可以帮助到各位。

  经过一个星期的死磕,Zabbix取数据和RRDtool绘图都弄清楚了,做第一运维平台的时候绘图取数据是直接从Zabbix的数据库取的,显得有点笨拙,不过借此也了解了Zabbix数据库结构还是有不少的收获。

  学习Zabbix的API官方文档少不了,官方文档地址链接https://www.zabbix.com/documentation/ 大家选择对应的版本就好了,不过2.0版本的API手册位置有点特别开始我还以为没有,后来找到了如下https://www.zabbix.com/documentation/2.0/manual/appendix/api/api 用ZabbixAPI取监控数据的思路大致是这样的,先获取所有监控的主机,再遍历每台主机获取每台主机的所有图形,最后获取每张图形每个监控对象(item)的最新的监控数据或者一定时间范围的数据。 下面按照上面的思路就一段一段的贴出我的程序代码:

  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

  ##################通用请求处理函数####################

  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、获取所有主机

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

  #获取所有主机和对应的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

  返回的结果是一个列表,每个元素是一个字典,字典的key代表主机名,value代表hostid

Zabbix与RRDtool绘图篇之用ZabbixAPI取监控数据 三联

  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']

  注意传入的参数是主机名而不是主机id,结果也是由字典组成的列表。

zabbixget02

  4、获取每张图的监控对象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