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在大数据时代,一切都要用数据来说话,大数据处理的过程一般需要经过以下的几个步骤 数据的采集和获取 数据的清洗,抽取,变形和装载 数据的分析,探索和预测 ...
随机推荐
- Maven <Profiles>定义不同环境的参数变量
记录一下 https://blog.csdn.net/qq245282209/article/details/52192115
- 每一行代码都有记录—如何用git一步步探索项目的历史
每一行代码都有一块被隐藏了的文档信息. 下面的代码片段不管是谁写的,其第4行因为某些原因要访问一个DOM结点的clientLeft属性,但却对结果不作任何处理.这十分的莫名其妙,你能告诉我他们为什么要 ...
- CRC16位校验
之前有跟第三方通讯合作,应为CRC表码问题导致校验出结果不一致,纠结了很久,最后直接采用CRC计算方式校验才解决. 两种方式贴,自行对比. CRC校验计算方法 private ushort CRC_1 ...
- jQuery补充知识点
链式编程 通常情况下,只有设置操作才能把链式变成延续下去.因为获取 操作的时候,会返回获取到的响应的值,无法反对jQuery对象. //end(); 筛选选择器会改变jQuery对象的DOM对象,想要 ...
- 安装jdk出现问题:Error opening registry key'software\Javasoft\Java Runti...
重装系统后发现jdk没有了,重新安装了,装一个其实挺容易的,但是“java -version”回车的时候,“啪”,error: Error opening registry key'software\ ...
- textarea 滚动条属性设置
转载:http://www.cnblogs.com/JensonBin/archive/2011/02/23/1962099.html scrollbar属性.样式详解1.overflow内容溢出时的 ...
- 撩课-Web大前端每天5道面试题-Day36
1.介绍一下你对浏览器内核的理解? 主要分成两部分:渲染引擎(layout engineer或Rendering Engine)和JS引擎. 渲染引擎:负责取得网页的内容(HTML.XML.图像等等) ...
- Android - 系统开机你知道多少?
https://github.com/zhantong/interview/blob/master/Android/Android.md#38-android%E7%B3%BB%E7%BB%9F%E5 ...
- @ModelAttribute注解详解
@ModelAttribute注解详解 1.@ModelAttribute定义: 被该注解定义的方法,会在该方法所在的controller的任何目标方法执行之前执行 2.@ModelAttribute ...
- Python paramiko ssh 在同一个session里run多个命令
import threading, paramiko strdata='' fulldata='' class ssh: shell = None client = None transport = ...