如何通过python获取zabbix中的graphql python报表

Python+Mysql生成zabbix统计数据 - 推酷
Python+Mysql生成zabbix统计数据
先大概了解一下zabbix数据库结构:
1、groups表
2、找到组ID就可以根据组ID找出这个组下面的所有服务器的ID,这个关系在hosts_groups表里面:
3、有了hostid就可以在hosts表里查看这台机器的基本信息了:
items表则可以根据hostid查出这台服务器的所有监控项:
4、终于在items表查到itemid,利用这个itemid在trends和trends_uint这两个表中统计出我们需要的数据
我python水平挺菜的,很多面向对象的功能都不知道咋用,求大神教育
#!/usr/bin/python
#coding:utf-8
import MySQLdb
import time,datetime
#zabbix数据库信息:
zdbhost = '192.168.1.1'
zdbuser = 'zabbix'
zdbpass = 'zabbixreport'
zdbport = 3306
zdbname = 'zabbix'
#需要查询的key列表
'trends_uint':[
'net.if.in[eth0]',
'net.if.out[eth0]',
'vfs.fs.size[/,used]',
'vm.memory.size[available]',
'trends':[
'system.cpu.load[percpu,avg5]',
'system.cpu.util[,idle]',
class ReportForm:
def __init__(self):
'''打开数据库连接'''
self.conn = MySQLdb.connect(host=zdbhost,user=zdbuser,passwd=zdbpass,port=zdbport,db=zdbname)
self.cursor = self.conn.cursor(cursorclass=MySQLdb.cursors.DictCursor)
#生成zabbix哪个分组报表
self.groupname = 'qjsh'
#获取IP信息:
self.IpInfoList = self.__getHostList()
def __getHostList(self):
'''根据zabbix组名获取该组所有IP'''
#查询组ID:
sql = '''select groupid from groups where name = '%s' ''' % self.groupname
self.cursor.execute(sql)
groupid = self.cursor.fetchone()['groupid']
#根据groupid查询该分组下面的所有主机ID(hostid):
sql = '''select hostid from hosts_groups where groupid = %s''' % groupid
self.cursor.execute(sql)
hostlist = self.cursor.fetchall()
#生成IP信息字典:结构为{'119.146.207.19':{'hostid':10086L,},}
IpInfoList = {}
for i in hostlist:
hostid = i['hostid']
sql = '''select host from hosts where status = 0 and hostid = %s''' % hostid
ret = self.cursor.execute(sql)
IpInfoList[self.cursor.fetchone()['host']] = {'hostid':hostid}
return IpInfoList
def __getItemid(self,hostid,itemname):
'''获取itemid'''
sql = '''select itemid from items where hostid = %s and key_ = '%s' ''' % (hostid, itemname)
if self.cursor.execute(sql):
itemid = self.cursor.fetchone()['itemid']
itemid = None
return itemid
def getTrendsValue(self,itemid, start_time, stop_time):
'''查询trends_uint表的值,type的值为min,max,avg三种'''
resultlist = {}
for type in ['min','max','avg']:
sql = '''select %s(value_%s) as result from trends where itemid = %s and clock &= %s and clock &= %s''' % (type, type, itemid, start_time, stop_time)
self.cursor.execute(sql)
result = self.cursor.fetchone()['result']
if result == None:
result = 0
resultlist[type] = result
return resultlist
def getTrends_uintValue(self,itemid, start_time, stop_time):
'''查询trends_uint表的值,type的值为min,max,avg三种'''
resultlist = {}
for type in ['min','max','avg']:
sql = '''select %s(value_%s) as result from trends_uint where itemid = %s and clock &= %s and clock &= %s''' % (type, type, itemid, start_time, stop_time)
self.cursor.execute(sql)
result = self.cursor.fetchone()['result']
if result:
resultlist[type] = int(result)
resultlist[type] = 0
return resultlist
def getLastMonthData(self,hostid,table,itemname):
'''根据hostid,itemname获取该监控项的值'''
#获取上个月的第一天和最后一天
ts_first = int(time.mktime(datetime.date(datetime.date.today().year,datetime.date.today().month-1,1).timetuple()))
lst_last = datetime.date(datetime.date.today().year,datetime.date.today().month,1)-datetime.timedelta(1)
ts_last = int(time.mktime(lst_last.timetuple()))
itemid = self.__getItemid(hostid, itemname)
function = getattr(self,'get%sValue' % table.capitalize())
function(itemid, ts_first, ts_last)
def getInfo(self):
#循环读取IP列表信息
for ip,resultdict in
zabbix.IpInfoList.items():
print &正在查询 IP:%-15s hostid:%5d 的信息!& % (ip, resultdict['hostid'])
#循环读取keys,逐个key统计数据:
for table, keylists in keys.items():
for key in keylists:
print &\t正在统计 key_:%s& % key
zabbix.getLastMonthData(resultdict['hostid'],table,key)
zabbix.IpInfoList[ip][key] = data
def writeToXls(self):
'''生成xls文件'''
import xlsxwriter
workbook = xlsxwriter.Workbook('damo.xls')
#创建工作薄
worksheet = workbook.add_worksheet()
#写入标题(第一行)
for value in [&主机&,&CPU平均空闲值&,&CPU最小空闲值&,&可用平均内存(单位M)&,&可用最小内存(单位M)&,&CPU5分钟负载&,&进入最大流量(单位Kbps)&,&进入平均流量(单位Kbps)&,&出去最大流量(单位Kbps)&,&出去平均流量(单位Kbps)&]:
worksheet.write(0,i, value.decode('utf-8'))
#写入内容:
for ip,value in self.IpInfoList.items():
worksheet.write(j,0, ip)
worksheet.write(j,1, '%.2f' % value['system.cpu.util[,idle]']['avg'])
worksheet.write(j,2, '%.2f' % value['system.cpu.util[,idle]']['min'])
worksheet.write(j,3, '%dM' % int(value['vm.memory.size[available]']['avg'] / 1024 / 1024))
worksheet.write(j,4, '%dM' % int(value['vm.memory.size[available]']['min'] / 1024 / 1024))
worksheet.write(j,5, '%.2f' % value['system.cpu.load[percpu,avg5]']['avg'])
worksheet.write(j,6, value['net.if.in[eth0]']['max']/1000)
worksheet.write(j,7, value['net.if.in[eth0]']['avg']/1000)
worksheet.write(j,8, value['net.if.out[eth0]']['max']/1000)
worksheet.write(j,9, value['net.if.out[eth0]']['avg']/1000)
workbook.close()
except Exception,e:
def __del__(self):
'''关闭数据库连接'''
self.cursor.close()
self.conn.close()
if __name__ == &__main__&:
zabbix = ReportForm()
zabbix.getInfo()
zabbix.writeToXls()
生成xls文件我用了一个叫xlsxwriter的第三方库,这个库只能写不能读,感觉还可以,生成出来的效果:
已发表评论数()
请填写推刊名
描述不能大于100个字符!
权限设置: 公开
仅自己可见
正文不准确
标题不准确
排版有问题
主题不准确
没有分页内容
图片无法显示
视频无法显示
与原文不一致【宗旨】 专注分享有味道,有深度,有宽度的运维干货.让运维工作变得简单,流畅.
<span class="tipso_style" id="tip-w" data-tipso=''>
浏览 749733
综合栏目关于本站 老蔡博客专注分享互联网前沿技术和深度运维工作经验、含有企业系统部署、软硬件性能监控、脚本编程、企业私有云等干货。在这里你可以畅所欲言,举杯邀月,结识志同道合的小伙伴...openstack(39)
Zabbix API开始扮演着越来越重要的角色,尤其是在集成第三方软件和自动化日常任务时。很难想象管理数千台服务器而没有自动化是多么的困难。Zabbix API为批量操作、第三方软件集成以及其他作用提供可编程接口。
Zabbix API是在1.8版本中开始引进并且已经被广泛应用。所有的Zabbix移动客户端都是基于API,甚至原生的WEB前端部分也是建立在它之上。Zabbix API 中间件使得架构更加模块化也避免直接对数据库进行操作。它允许你通过JSON RPC协议来创建、更新和获取Zabbix对象并且做任何你喜欢的操作【当然前提是你拥有认证账户】。
Zabbix API提供两项主要功能:
远程管理Zabbix配置
远程检索配置和历史数据
API 采用JSON-RPC实现。这意味着调用任何函数,都需要发送POST请求,输入输出数据都是以JSON&#26684;式。大致工作流如下:
准备JSON对象,它描述了你想要做什么(创建主机,获取图像,更新监控项等)。
采用POST方法向/zabbix/api_jsonrpc.php发送此JSON对象. /zabbix/是Zabbix前端地址。api_jsonrpc.php是调用API的PHP脚本。可在安装可视化前端的目录下找到。
获取JSON&#26684;式响应。
注:请求除了必须是POST方法之外,HTTP Header Content-Type必须为【application/jsonrequest,application/json-rpc,application/json】其中之一。
可以采用脚本或者任何&手动&支持JSON RPC的工具来使用API。而首先需要了解的就是如何验证和如何使用验证ID来获取想要的信息。后面的演示会以Python脚本和基于Curl的例子来呈现API的基本使用。
基本请求&#26684;式
Zabbix API 简化的JSON请求如下:
&jsonrpc&: &2.0&,
&method&: &method.name&,&
&params&: {
&param_1_name&: &param_1_value&,
&param_2_name&: &param_2_value&&
&auth&: &d19a9b4b55d49e30cf12b81&,
下面一行一行来看:
&jsonrpc&: &2.0&-这是标准的JSON RPC参数以标示协议版本。所有的请求都会保持不变。
&method&: &method.name&-这个参数定义了真实执行的操作。例如:host.create、item.update等等
&params&-这里通过传递JSON对象来作为特定方法的参数。如果你希望创建监控项,&name&和&key_&参数是需要的,每个方法需要的参数在Zabbix API文档中都有描述。
&id&: 1-这个字段用于绑定JSON请求和响应。响应会跟请求有相同的&id&。在一次性发送多个请求时很有用,这些也不需要唯一或者连续
&auth&: &d19a9b4b55d49e30cf12b81&-这是一个认证令牌【authentication token】用以鉴别用户、访问API。这也是使用API进行相关操作的前提-获取认证ID。
2 使用python urllib2 和 url调用 API
2.1 安装Zabbix
& & & &参考:ubuntu下安装zabbix: http://blog.csdn.net/zhaihaifei/article/details/
Zabbix API是基于JSON-RPC 2.0规&#26684;,具体实现可以选择任何你喜欢的编程语言或者手动方式。这里我们采用的Python和基于Curl的方式来做示例。Python 2.7版本已经支持JSON,所以不再需要其他模块组件。当然可以采用Perl、Ruby、PHP之类的语言,使用前先确保相应JSON模块的安装。
任何Zabbix API客户端在真正工作之前都需要验证它自身。在这里是采用User.login方法。这个方法接受一个用户名和密码作为参数并返回验证ID,一个安全哈希串用于持续的API调用(在使用User.logout之前该验证ID均有效)。具体Python代码auth.py如下:
#!/usr/bin/env python2.7
#coding=utf-8
import json
import urllib2
# based url and required header
url = &/api_jsonrpc.php&
header = {&Content-Type&: &application/json&}
# auth user and password
data = json.dumps(
&jsonrpc&: &2.0&,
&method&: &user.login&,
&params&: {
&user&: &Admin&,
&password&: &zabbix&
# create request object
request = urllib2.Request(url,data)
for key in header:
request.add_header(key,header[key])
# auth and get authid
result = urllib2.urlopen(request)
except URLError as e:
print &Auth Failed, Please Check Your Name And Password:&,e.code
response = json.loads(result.read())
result.close()
print &Auth Successful. The Auth ID Is:&,response[&#39;result&#39;]
这里需要确保URL中的用户名和密码匹配。下面是运行结果:
可以看到,auth.py成功连接并认证。现在有了验证ID,它能够在新的API调用中被重用。
下面再来看基于CURL的方式来进行验证是如何实现的:
test@test:~$ curl -i -X POST -H &#39;Content-Type:application/json&#39;
-d&#39;{&jsonrpc&: &2.0&,&method&:&user.authenticate&,&params&:{&user&:&Admin&,&password&:&zabbix&},&auth&: null,&id&:0}&#39;
http://10.0.2.6/zabbix/api_jsonrpc.php
HTTP/1.1 200 OK
Date: Fri, 28 Oct :54 GMT
Server: Apache/2.4.7 (Ubuntu)
X-Powered-By: PHP/5.5.9-1ubuntu4.20
Content-Length: 68
Content-Type: application/json
{&jsonrpc&:&2.0&,&result&:&30fee9cdd05ef571a95ec26&,&id&:0}
这里举例说明如何获取监控主机列表【host list】。这段脚本需要采用auth.py中获取的验证ID并执行host.get方法来获取主机列表。来看具体代码get_host.py:
#!/usr/bin/env python2.7
#coding=utf-8
import json
import urllib2
# based url and required header
url = &http://10.0.2.6/zabbix/api_jsonrpc.php&
header = {&Content-Type&: &application/json&}
# request json
data = json.dumps(
&jsonrpc&:&2.0&,
&method&:&host.get&,
&params&:{
&output&:[&hostid&,&name&],
&filter&:{&host&:&&}
&auth&:&533b713d9ac36fc1f0eb&, # the auth id is what auth script returns, remeber it is string
# create request object
request = urllib2.Request(url,data)
for key in header:
request.add_header(key,header[key])
# get host list
result = urllib2.urlopen(request)
except URLError as e:
if hasattr(e, &#39;reason&#39;):
print &#39;We failed to reach a server.&#39;
print &#39;Reason: &#39;, e.reason
elif hasattr(e, &#39;code&#39;):
print &#39;The server could not fulfill the request.&#39;
print &#39;Error code: &#39;, e.code
response = json.loads(result.read())
result.close()
print &Number Of Hosts: &, len(response[&#39;result&#39;])
for host in response[&#39;result&#39;]:
print &Host ID:&,host[&#39;hostid&#39;],&Host Name:&,host[&#39;name&#39;]
对比基于CURL的访问方式:&
curl -i -X POST -H &#39;Content-Type: application/json&#39; -d &#39;{&jsonrpc&:&2.0&,&method&:&host.get&,&params&:{&output&:[&hostid&,&name&],&filter&:{&host&:&&}},&auth&:&533b713d9ac36fc1f0eb&,&id&:1}&#39; http://10.0.2.6/zabbix/api_jsonrpc.php
test@test:~$ curl -i -X POST -H &#39;Content-Type: application/json&#39; -d &#39;{&jsonrpc&:&2.0&,&method&:&host.get&,&params&:{&output&:[&hostid&,&name&],&filter&:{&host&:&&}},&auth&:&533b713d9ac36fc1f0eb&,&id&:1}&#39; http://10.0.2.6/zabbix/api_jsonrpc.php
HTTP/1.1 200 OK
Date: Thu, 27 Oct :21 GMT
Server: Apache/2.4.7 (Ubuntu)
X-Powered-By: PHP/5.5.9-1ubuntu4.20
Content-Length: 114
Content-Type: application/json
{&jsonrpc&:&2.0&,&result&:[{&hostid&:&10084&,&name&:&Zabbix server&},{&hostid&:&10105&,&name&:&10.0.2.7&}],&id&:1}
比较来看,
采用脚本可以有更多的灵活性,
基于CURL的方式,对结果的处理不是很方便。
原理则都是相通的。
除了这些获取信息以外,采用API调用同样可以进行创建操作,更新操作和删除操作等等。这也很容易让我们联想起数据库操作,当然比较这些采用API调用获取结果的方式,也不能忘掉这种最直接而危险的方式。在开始讨论中已经提到,Zabbix现在自带的前端实现部分是采用数据库操作,部分是基于API调用。在API还不是很成熟的现在,具体采用哪种方式,需要根据业务需求再来确定。
3 使用requests包来调用API
test@test:~$ python
Python 2.7.6 (default, Mar 22 :56)
[GCC 4.8.2] on linux2
Type &help&, &copyright&, &credits& or &license& for more information.
&&& import requests
&&& url = &http://10.0.2.6/zabbix/api_jsonrpc.php&
&&& header = {&Content-Type&: &application/json&}
&&& r.status_code
&&& r.text
u&#39;{&jsonrpc&:&2.0&,&error&:{&code&:-32700,&message&:&Parse error&,&data&:&Invalid JSON. An error occurred on the server while parsing the JSON text.&},&id&:null}&#39;
&&& r = requests.get(url, headers=header, auth=(&#39;admin&#39;, &#39;zabbix&#39;))
&&& r.status_code
&&& r.text
u&#39;{&jsonrpc&:&2.0&,&error&:{&code&:-32700,&message&:&Parse error&,&data&:&Invalid JSON. An error occurred on the server while parsing the JSON text.&},&id&:null}&#39;
&&& import json
&&& payload = {&jsonrpc&: &2.0&,&method&:&user.login&,&params&:{&user&:&Admin&,&password&:&zabbix&},&auth&: &null&,&id&: &0&}
&&& r = requests.post(url, headers=header, params=json.dumps(payload))
&&& r.text
u&#39;{&jsonrpc&:&2.0&,&error&:{&code&:-32700,&message&:&Parse error&,&data&:&Invalid JSON. An error occurred on the server while parsing the JSON text.&},&id&:null}&#39;
&&& r = requests.get(url, headers=header, data=json.dumps(payload))
&&& r.text
u&#39;{&jsonrpc&:&2.0&,&error&:{&code&:-32602,&message&:&Invalid params.&,&data&:&Not authorized&},&id&:&0&}&#39;
&&& payload = {&jsonrpc&: &2.0&,&method&:&user.login&,&params&:{&user&:&Admin&,&password&:&zabbix&},&id&: 100}
&&& r = requests.get(url, headers=header, data=json.dumps(payload))
&&& r.text
u&#39;{&jsonrpc&:&2.0&,&result&:&d741dc8b1f9abfc04c5efd8a9d0f7375&,&id&:100}&#39;
&&& 关于requests的使用, 参考:
1 &python的requests初步使用&https://my.oschina.net/yangyanxing/blog/280029
2&http://cn.python-requests.org/zh_CN/latest/user/quickstart.html
ubuntu下安装zabbix: http://blog.csdn.net/zhaihaifei/article/details/
参考知识库
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
访问:169606次
积分:2598
积分:2598
排名:第11504名
原创:94篇
转载:83篇
(7)(7)(5)(4)(1)(2)(10)(1)(21)(17)(2)(5)(3)(1)(5)(5)(3)(5)(15)(5)(3)(7)(3)(15)(3)(3)(1)(1)(2)(4)(7)(2)(3)

我要回帖

更多关于 python pygraphviz 的文章

 

随机推荐