Zabbix and RRDtool drawing pieces of the use of ZABBIXAPI to take monitoring data

Source: Internet
Author: User
Tags api manual auth manual documentation error code json rrdtool split

Let's take a look at a Zabbix and RRDtool drawing zabbixapi use of the monitoring data technology article, I hope that the following can help you.

After one weeks of death knock, Zabbix data and RRDtool drawing are clear, do the first operation of the platform when drawing data is directly from the Zabbix database, it is a bit clumsy, but also understand the ZABBIX database structure is still a lot of harvest.

Learn Zabbix API official documents, the official document Address link https://www.zabbix.com/documentation/people choose the corresponding version of the good, However, the 2.0 version of the API manual location is a bit special at first I thought no, and then found the following HTTPS://WWW.ZABBIX.COM/DOCUMENTATION/2.0/MANUAL/APPENDIX/API/API The idea of using ZABBIXAPI to take monitoring data is roughly like this, first get all the monitored host, then traverse each host to get all the graphics of each host, and finally get the latest monitoring data or a certain time range data for each monitor object (item) of each graph. Follow the above ideas for a paragraph of the post my program code:

1, login Zabbix to obtain communication 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": "username", "password": "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. Get all the Hosts

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

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

The result returned is a list, each element is a dictionary, the dictionary key represents the host name, and the value represents HostID

3, get each of the graphics of each host

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

#查找一台主机的所有图形和图形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, containing HostID

Return res[0][' graphs ']

Note that the incoming parameter is a host name rather than a host ID, and the result is a list of dictionaries.

4, get each map of the Monitoring object item

#可以返回完整信息rs, containing 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

The returned data already contains the latest monitoring data value and the timestamp of the value, if only need to take the latest monitoring data, here is actually OK, remember this time the incoming parameter is Graphid.

5, according to the Itemid to obtain more monitoring data

Here are 10 monitoring data, you can change the parameters to obtain more data, all by their own needs.

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

#获取历史数据, history must assign the correct type 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

All of the above code adds up to a Zabbix class that takes data. The extracted data can be used for rrdtool drawing or other purposes.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.