Python抓取zabbix性能监控图
一、通过查询zabbix db的方式通过主机IP获取到所需要的graphid(比如CPU监控图、内存监控图等,每个图对应一个graphid),最后将图片保存到本地
注:该graph必须要在 screen中存在才可以获取到相应的graphid,否则graphid为空。
- import urllib2,requests,cookielib,urllib
- #定义登录地址
- login_url = 'http://10.16.2.4/zabbix/index.php'
- #定义登录所需要用的信息,如用户名、密码等,使用urllib进行编码
- login_data = urllib.urlencode({
- "name": 'admin',
- "password": 'password',
- "autologin": 1,
- "enter": "Sign in"})
- #设置一个cookie处理器,它负责从服务器下载cookie到本地,并且在发送请求时带上本地的cookie
- cj = cookielib.CookieJar()
- opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
- urllib2.install_opener(opener)
- opener.open(login_url,login_data).read()
- #这部分没有具体写
- sql_hostid = select hostid from hosts where host='10.16.3.2'; #通过host查询hostid
- sql_itemid = select itemid,`name`,key_ from items where hostid='' #通过hostid查询itemid,通过key_过滤性能监视器
- sql_graphid = select graphid from graphs_items where itemid='' #通过itemid查询对应的graphid
- graph_args = urllib.urlencode({
- "graphid":'',
- "width":'',
- "height":'',
- "stime":'', #图形开始时间
- "period":''})
- graph_url = 'http://10.16.2.4/zabbix/chart2.php'
- print graph_args #返回格式:width=400&screenid=28&graphid=4769&period=86400&height=156
- data = opener.open(graph_url,graph_args).read()
- # print data
- file=open('d:\\zaa225.png','wb')
- file.write(data)
- file.flush()
- file.close()
二、通过zabbix API获取graphID,最后将图片保存到本地以当前日期为名的文件夹中,实现多线程并发:
- # -*- coding: UTF-8 -*-
- import urllib2,json,cookielib,urllib,datetime,os,threading
- from urllib2 import Request, urlopen, URLError, HTTPError
- global auth_code,zabbix_url,zabbix_header,login_url,graph_url,login_data,pic_save_path_dir,yesterday9,opener
- #zabbix接口地址、登录地址、图片地址
- zabbix_url="http://10.16.2.4/zabbix/api_jsonrpc.php"
- login_url = 'http://10.16.2.4/zabbix/index.php'
- graph_url = 'http://10.16.2.4/zabbix/chart2.php'
- zabbix_header = {"Content-Type":"application/json"}
- zabbix_user = "admin"
- zabbix_pass = "password"
- auth_code = ""
- auth_data = json.dumps({
- "jsonrpc":"2.0",
- "method":"user.login",
- "params":
- {
- "user":zabbix_user,
- "password":zabbix_pass
- },
- "id":0
- })
- #定义登录所需要用的信息,如用户名、密码等,使用urllib进行编码
- login_data = urllib.urlencode({
- "name": zabbix_user,
- "password": zabbix_pass,
- "autologin": 1,
- "enter": "Sign in"})
- #新建以当天日期为名的文件夹保存图片
- today = datetime.datetime.now().date().strftime('%Y%m%d')
- pic_save_path_dir= os.path.join('d:\\pic',today ) #修改图片保存位置
- if not os.path.exists(pic_save_path_dir):
- os.makedirs(pic_save_path_dir)
- #定义graph的starttime参数,从前一天的9:00开始
- yesterday = (datetime.datetime.now()-datetime.timedelta(days=1))
- yesterday9 = datetime.datetime(yesterday.year,yesterday.month,yesterday.day,9).strftime('%Y%m%d%H%M%S')
- #登录zabbix,设置一个cookie处理器,负责从服务器下载cookie到本地,并且在发送请求时带上本地的cookie
- cj = cookielib.CookieJar()
- opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
- urllib2.install_opener(opener)
- opener.open(login_url,login_data)#.read()
- request = urllib2.Request(zabbix_url,auth_data)
- for key in zabbix_header:
- request.add_header(key,zabbix_header[key])
- try:
- result = urllib2.urlopen(request)
- except HTTPError, e:
- print 'The server couldn\'t fulfill the request, Error code: ', e.code
- except URLError, e:
- print 'We failed to reach a server.Reason: ', e.reason
- else:
- response=json.loads(result.read())
- #print response
- result.close()
- #判断SESSIONID是否在返回的数据中
- if 'result' in response:
- auth_code=response['result']
- else:
- print response['error']['data']
- def Http_access(data):
- request = urllib2.Request(zabbix_url,data)
- for key in zabbix_header:
- request.add_header(key,zabbix_header[key])
- result = urllib2.urlopen(request)
- response = json.loads(result.read())
- # print result.read()
- # print response
- result.close()
- if len(response['result']) > 0:
- return response['result'][0]
- def get_hostid(ip):
- get_host_data = ''
- if len(auth_code) <> 0:
- get_host_data = json.dumps({
- "jsonrpc": "2.0",
- "method": "host.get",
- "params": {
- "output": "extend",
- "filter": {
- "host": [
- ip,
- ]
- }
- },
- "auth": auth_code,
- "id": 1
- })
- return get_host_data
- def get_itemid(hostid,itemtype):
- get_item_data = ''
- if (len(auth_code) <> 0) and (hostid is not None):
- get_item_data = json.dumps({
- "jsonrpc": "2.0",
- "method": "item.get",
- "params": {
- "output": "extend",
- "hostids": hostid,
- "search":{
- "name": itemtype
- },
- "sortfield": "name"
- },
- "auth": auth_code,
- "id": 1
- })
- return get_item_data
- def get_graphid(itemid):
- get_graph_data = ''
- if (len(auth_code) <> 0) and (itemid is not None):
- get_graph_data = json.dumps({
- "jsonrpc": "2.0",
- "method": "graphitem.get",
- "params": {
- "output": "extend",
- "expandData": 1,
- "itemids": itemid
- },
- "auth": auth_code,
- "id": 1
- })
- return get_graph_data
- def pic_save(ip,name,graphid):
- graph_args = urllib.urlencode({
- "graphid":graphid,
- "width":'', #定义图片宽度
- "height":'', #定义图片高度
- "stime":yesterday9, #图形开始时间
- "period":''}) #定义时长,取1天的数据
- data = opener.open(graph_url,graph_args).read()
- #pic_save_path = pic_save_path_dir + ip + '-' + name +'.png'
- picname = ip + '-' + name +'.png'
- pic_save_path = os.path.join(pic_save_path_dir,picname)
- file=open(pic_save_path,'wb')
- file.write(data)
- #file.flush()
- file.close()
- #多线程并发调用该函数
- def pic_save_th(ip):
- #根据ip获取hostid
- host_data = get_hostid(ip)
- host_result = Http_access(host_data)
- if host_result is not None: #判断该IP是否在zabbix中存在
- hostid = host_result['hostid']
- #根据监视器名称获取相应的itemid
- cpuname = 'CPU Usage'
- memoryname = 'Memory - Memory available'
- diskname = 'Disk - Current Disk Queue Length'
- netcard = 'Traffic for Public Receive'
- item_cpu = get_itemid(hostid,cpuname)
- item_memory = get_itemid(hostid,memoryname)
- item_disk = get_itemid(hostid,diskname)
- item_netcard = get_itemid(hostid,netcard)
- itemid_cpu = Http_access(item_cpu)['itemid']
- itemid_memory = Http_access(item_memory)['itemid']
- itemid_disk = Http_access(item_disk)['itemid']
- itemid_netcard = Http_access(item_netcard)['itemid']
- #根据itemid获取相应的graphid
- graphdata_cpu = get_graphid(itemid_cpu)
- graphdata_memory = get_graphid(itemid_memory)
- graphdata_disk = get_graphid(itemid_disk)
- graphdata_netcard = get_graphid(itemid_netcard)
- graphid_cpu = Http_access(graphdata_cpu)['graphid']
- graphid_memory = Http_access(graphdata_memory)['graphid']
- graphid_disk = Http_access(graphdata_disk)['graphid']
- graphid_netcard = Http_access(graphdata_netcard)['graphid']
- print ip#,graphid_cpu,graphid_memory,graphid_disk,graphid_netcard
- #调用pic_save函数保存图片到本地
- pic_save(ip,cpuname,graphid_cpu)
- pic_save(ip,memoryname,graphid_memory)
- pic_save(ip,diskname,graphid_disk)
- pic_save(ip,netcard,graphid_netcard)
- else:
- print '%s doesnot exist in zabbix' %ip
- #定义线程数控制函数,num表示每次并发的线程数
- def lstg(num,lst):
- #定义每段的个数num
- l = len(lst)
- g = l/num #取分成几组
- last = l%num #判断是否有剩余的数
- lstn = []
- if num >= l:
- lstn.append(lst)
- else:
- for i in range(g):
- i=i+1
- n=i*num
- m=n-num
- lstn.append(lst[m:n])
- if last <> 0:
- lstn.append(lst[-last:])
- return lstn
- # serverip=['10.160.26.30','10.160.26.31','10.160.26.32']
- # for ip in serverip:
- # pic_save_th(ip)
- if __name__ =='__main__':
- #定义线程数量
- tnum = 5
- serverips=['10.160.26.30','10.160.26.31','10.160.26.32','10.160.31.31','10.160.31.32','10.160.31.36','10.160.34.250','10.160.34.251','192.168.200.250','192.168.200.251']
- for ips in lstg(tnum,serverips):
- threads=[]
- for ip in ips:
- #创建并启动进程
- t = threading.Thread(target=pic_save_th,args=(ip,))
- #t.setName('th-'+ ip)
- t.setDaemon(True)
- t.start()
- threads.append(t)
- #等待每个线程结束
- for t in threads:
- #print t.name,t.is_alive(),ctime()
- t.join()
Python抓取zabbix性能监控图的更多相关文章
- python抓取zabbix图形,并发送邮件
最近十九大非常烦,作为政府网站维护人员,简直是夜不能寐.各种局子看着你,内保局,公安部,360,天融信,华胜天成,中央工委,政治委员会... 360人员很傻X,作为安全公司,竟然不能抓到XX网站流量, ...
- python抓取不得姐动图(报错 urllib.error.HTTPError: HTTP Error 403: Forbidden)
抓取不得姐动图(报错) # -*- coding:utf-8 -*- #__author__ :kusy #__content__:文件说明 #__date__:2018/7/23 17:01 imp ...
- python抓取性感尤物美女图
由于是只用标准库,装了python3运行本代码就能下载到多多的美女图... 写出代码前面部分的时候,我意识到自己的函数设计错了,强忍继续把代码写完. 测试发现速度一般,200K左右的下载速度,也没有很 ...
- Python爬虫之三种网页抓取方法性能比较
下面我们将介绍三种抓取网页数据的方法,首先是正则表达式,然后是流行的 BeautifulSoup 模块,最后是强大的 lxml 模块. 1. 正则表达式 如果你对正则表达式还不熟悉,或是需要一些提 ...
- 如何用python抓取js生成的数据 - SegmentFault
如何用python抓取js生成的数据 - SegmentFault 如何用python抓取js生成的数据 1赞 踩 收藏 想写一个爬虫,但是需要抓去的的数据是js生成的,在源代码里看不到,要怎么才能抓 ...
- 使用Python抓取猫眼近10万条评论并分析
<一出好戏>讲述人性,使用Python抓取猫眼近10万条评论并分析,一起揭秘“这出好戏”到底如何? 黄渤首次导演的电影<一出好戏>自8月10日在全国上映,至今已有10天,其主演 ...
- python抓取知乎热榜
知乎热榜讨论话题,https://www.zhihu.com/hot,本文用python抓取下来分析 #!/usr/bin/python # -*- coding: UTF-8 -*- from ur ...
- Python 抓取网页并提取信息(程序详解)
最近因项目需要用到python处理网页,因此学习相关知识.下面程序使用python抓取网页并提取信息,具体内容如下: #---------------------------------------- ...
- 使用 Python 抓取欧洲足球联赛数据
Web Scraping在大数据时代,一切都要用数据来说话,大数据处理的过程一般需要经过以下的几个步骤 数据的采集和获取 数据的清洗,抽取,变形和装载 数据的分析,探索和预测 ...
随机推荐
- vim中使用系统粘贴板
在vim中如果想使用系统粘贴板,也就是说,如果你在其他程序中复制内容,那么使用shift+insert组合键就可以粘贴进来. 需要说明的是,vim中的粘贴板有很多,你可以输入 :reg来进行查看.而我 ...
- Python中创建守护进程
python 创建守护进程 python 的os.setdid()提供了类似linux c api的 setsid 也可以通过unix双fork创建守护进程. 几个相关的函数 os.umask(0) ...
- zoj 2818 Root of the Problem(数学思维题)
题目链接: http://acm.zju.edu.cn/onlinejudge/showProblem.do?problemCode=2818 题目描述: Given positive integer ...
- 从Spring-Session源码看Session机制的实现细节
Re:从零开始的Spring Session(一) Re:从零开始的Spring Session(二) Re:从零开始的Spring Session(三) 去年我曾经写过几篇和 Spring Sess ...
- (原)SQL Server 代理作业执行持续时间简述
本文目录列表: 1.SQL Server 代理作业概述2.获取代理作业执行时间方法一 3.获取代理作业执行时间方法二4.总结语 5.参考目录清单列表 正文: 1.SQL Server 代理作业概述 ...
- WPF备忘录(5)怎样修改模板中的控件
首先,想问大家一个问题,你们如果要给一个Button添加背景图片会怎么做?(呵呵,这个问题又点小白哈) 是这样吗? <Button Height="57" Horizonta ...
- Springmvx拦截html出现406解决以及Server Tomcat v8.0 Server at localhost failed to start 问题解决方法
问题是这样的:环境是SSM框架,在配置好的框架里想请求一个html,结果406了,406就是HTTP协议状态码的一种,表示无法使用请求的特性来响应请求的网页.一般指客户端浏览器不接受所请求页面的MIM ...
- Spring全家桶系列–[SpringBoot入门到跑路]
//本文作者:cuifuan Spring全家桶————[SpringBoot入门到跑路] 对于之前的Spring框架的使用,各种配置文件XML.properties一旦出错之后错误难寻,这也是为什么 ...
- POJ3281(KB11-B 最大流)
Dining Time Limit: 2000MS Memory Limit: 65536K Total Submissions: 19170 Accepted: 8554 Descripti ...
- js-权威指南学习笔记19
第十九章 jQuery类库 1.传递HTML文本字符串给$()方法,jQuery会根据传入的文本创建好HTML元素并封装为jQuery对象返回. 2.想要遍历jQuery对象中的所有元素时,可以调用e ...