欢迎登陆真网站,您的到来是我们的荣幸。 登陆 注册 忘记密码? ☆设为首页 △加入收藏
欢迎加入真幸福QQ群
电脑知识: 基础知识 网络技术 操作系统 办公软件 电脑维修 电脑安全 windows7 windows8 windows10 服务器教程 平板电脑 视频播放教程 网络应用 互联网 工具软件 浏览器教程 QQ技巧 输入法教程 影视制作 YY教程 wps教程 word教程 Excel教程 PowerPoint
云南西双版纳特产小花糯玉米真空包装


linux中安装Zend Optimizer与eAccelerator教程
php5.3.10的安装配置步骤详解
linux下查看nginx、apache、mysql、php的编译参数
人生壁纸带你一同踏青
Win10系统如何清理旧系统备份文件Windows.old
Win10系统 9926预览版运行Steam崩溃的处理方法
Mac OS X如何校验文件的SHA1值以解决文件缺失问题
WinXP如何自动清理Temp文件夹以提高系统运行速度
Win10 Microsoft管理控制台停止工作的解决方法
要的就是独一无二,人生壁纸随你换
Zabbix与RRDtool绘图篇之用ZabbixAPI取监控数据
【 来源:网络 】【 点击:1 】 【 发布时间:2017_03_03 08:59:59 】

  一起来看一个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 = "http://xxx.xxx.xxx.xxx: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

  返回的数据已经包含了最新的一次监控数据的值和取值的时间戳,如果只需要取最新的监控数据,到这里其实就可以了,记得这次传入的参数是graphid。

zabbixget03

  5、根据itemid取得更多的监控数据

  下面是取10条监控数据,可以任意更改参数获取更多的数据,全凭自己所需了。

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

  #获取历史数据,history必须赋值正确的类型0,1,2,3,4 float,string,log,integer,text

  def history_get(self, itemid, i):

  data = json.dumps({

  "jsonrpc": "2.0",

  "method": "history.get",

  "params": { "output": "extend",

  "history": i,

  "itemids": itemid,

  "sortfield": "clock",

  "sortorder": "DESC",

  "limit": 10},

  "auth": self.authID,

  "id": 1})

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

  return res

zabbixget04

 

  上面的所有代码加起来就是一个Zabbix取数据的类。取出来的数据可以用RRDtool绘图或做其它用途了

本网站由川南居提供技术支持,fkzxf版权所有 浙ICP备12031891号
淳安分站 淳安分站