一、通过查询zabbix db的方式通过主机IP获取到所需要的graphid(比如CPU监控图、内存监控图等,每个图对应一个graphid),最后将图片保存到本地

注:该graph必须要在 screen中存在才可以获取到相应的graphid,否则graphid为空。

  1. import urllib2,requests,cookielib,urllib
  2. #定义登录地址
  3. login_url = 'http://10.16.2.4/zabbix/index.php'
  4. #定义登录所需要用的信息,如用户名、密码等,使用urllib进行编码
  5. login_data = urllib.urlencode({
  6. "name": 'admin',
  7. "password": 'password',
  8. "autologin": 1,
  9. "enter": "Sign in"})
  10.  
  11. #设置一个cookie处理器,它负责从服务器下载cookie到本地,并且在发送请求时带上本地的cookie
  12. cj = cookielib.CookieJar()
  13. opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
  14. urllib2.install_opener(opener)
  15. opener.open(login_url,login_data).read()
  16. #这部分没有具体写
  17. sql_hostid = select hostid from hosts where host='10.16.3.2'; #通过host查询hostid
  18. sql_itemid = select itemid,`name`,key_ from items where hostid='' #通过hostid查询itemid,通过key_过滤性能监视器
  19. sql_graphid = select graphid from graphs_items where itemid='' #通过itemid查询对应的graphid
  20.  
  21. graph_args = urllib.urlencode({
  22. "graphid":'',
  23. "width":'',
  24. "height":'',
  25. "stime":'', #图形开始时间
  26. "period":''})
  27.  
  28. graph_url = 'http://10.16.2.4/zabbix/chart2.php'
  29. print graph_args #返回格式:width=400&screenid=28&graphid=4769&period=86400&height=156
  30.  
  31. data = opener.open(graph_url,graph_args).read()
  32. # print data
  33. file=open('d:\\zaa225.png','wb')
  34. file.write(data)
  35. file.flush()
  36. file.close()

二、通过zabbix API获取graphID,最后将图片保存到本地以当前日期为名的文件夹中,实现多线程并发:

  

  1. # -*- coding: UTF-8 -*-
  2. import urllib2,json,cookielib,urllib,datetime,os,threading
  3. from urllib2 import Request, urlopen, URLError, HTTPError
  4. global auth_code,zabbix_url,zabbix_header,login_url,graph_url,login_data,pic_save_path_dir,yesterday9,opener
  5. #zabbix接口地址、登录地址、图片地址
  6. zabbix_url="http://10.16.2.4/zabbix/api_jsonrpc.php"
  7. login_url = 'http://10.16.2.4/zabbix/index.php'
  8. graph_url = 'http://10.16.2.4/zabbix/chart2.php'
  9.  
  10. zabbix_header = {"Content-Type":"application/json"}
  11. zabbix_user = "admin"
  12. zabbix_pass = "password"
  13. auth_code = ""
  14. auth_data = json.dumps({
  15. "jsonrpc":"2.0",
  16. "method":"user.login",
  17. "params":
  18. {
  19. "user":zabbix_user,
  20. "password":zabbix_pass
  21. },
  22. "id":0
  23. })
  24.  
  25. #定义登录所需要用的信息,如用户名、密码等,使用urllib进行编码
  26. login_data = urllib.urlencode({
  27. "name": zabbix_user,
  28. "password": zabbix_pass,
  29. "autologin": 1,
  30. "enter": "Sign in"})
  31.  
  32. #新建以当天日期为名的文件夹保存图片
  33. today = datetime.datetime.now().date().strftime('%Y%m%d')
  34. pic_save_path_dir= os.path.join('d:\\pic',today ) #修改图片保存位置
  35. if not os.path.exists(pic_save_path_dir):
  36. os.makedirs(pic_save_path_dir)
  37.  
  38. #定义graph的starttime参数,从前一天的9:00开始
  39. yesterday = (datetime.datetime.now()-datetime.timedelta(days=1))
  40. yesterday9 = datetime.datetime(yesterday.year,yesterday.month,yesterday.day,9).strftime('%Y%m%d%H%M%S')
  41.  
  42. #登录zabbix,设置一个cookie处理器,负责从服务器下载cookie到本地,并且在发送请求时带上本地的cookie
  43. cj = cookielib.CookieJar()
  44. opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
  45. urllib2.install_opener(opener)
  46. opener.open(login_url,login_data)#.read()
  47.  
  48. request = urllib2.Request(zabbix_url,auth_data)
  49. for key in zabbix_header:
  50. request.add_header(key,zabbix_header[key])
  51. try:
  52. result = urllib2.urlopen(request)
  53. except HTTPError, e:
  54. print 'The server couldn\'t fulfill the request, Error code: ', e.code
  55. except URLError, e:
  56. print 'We failed to reach a server.Reason: ', e.reason
  57. else:
  58. response=json.loads(result.read())
  59. #print response
  60. result.close()
  61.  
  62. #判断SESSIONID是否在返回的数据中
  63. if 'result' in response:
  64. auth_code=response['result']
  65. else:
  66. print response['error']['data']
  67.  
  68. def Http_access(data):
  69. request = urllib2.Request(zabbix_url,data)
  70. for key in zabbix_header:
  71. request.add_header(key,zabbix_header[key])
  72. result = urllib2.urlopen(request)
  73.  
  74. response = json.loads(result.read())
  75. # print result.read()
  76. # print response
  77. result.close()
  78. if len(response['result']) > 0:
  79. return response['result'][0]
  80.  
  81. def get_hostid(ip):
  82. get_host_data = ''
  83. if len(auth_code) <> 0:
  84. get_host_data = json.dumps({
  85. "jsonrpc": "2.0",
  86. "method": "host.get",
  87. "params": {
  88. "output": "extend",
  89. "filter": {
  90. "host": [
  91. ip,
  92. ]
  93. }
  94. },
  95. "auth": auth_code,
  96. "id": 1
  97. })
  98. return get_host_data
  99.  
  100. def get_itemid(hostid,itemtype):
  101. get_item_data = ''
  102. if (len(auth_code) <> 0) and (hostid is not None):
  103. get_item_data = json.dumps({
  104. "jsonrpc": "2.0",
  105. "method": "item.get",
  106. "params": {
  107. "output": "extend",
  108. "hostids": hostid,
  109. "search":{
  110. "name": itemtype
  111. },
  112. "sortfield": "name"
  113. },
  114. "auth": auth_code,
  115. "id": 1
  116. })
  117. return get_item_data
  118.  
  119. def get_graphid(itemid):
  120. get_graph_data = ''
  121. if (len(auth_code) <> 0) and (itemid is not None):
  122. get_graph_data = json.dumps({
  123. "jsonrpc": "2.0",
  124. "method": "graphitem.get",
  125. "params": {
  126. "output": "extend",
  127. "expandData": 1,
  128. "itemids": itemid
  129. },
  130. "auth": auth_code,
  131. "id": 1
  132. })
  133. return get_graph_data
  134.  
  135. def pic_save(ip,name,graphid):
  136. graph_args = urllib.urlencode({
  137. "graphid":graphid,
  138. "width":'', #定义图片宽度
  139. "height":'', #定义图片高度
  140. "stime":yesterday9, #图形开始时间
  141. "period":''}) #定义时长,取1天的数据
  142.  
  143. data = opener.open(graph_url,graph_args).read()
  144. #pic_save_path = pic_save_path_dir + ip + '-' + name +'.png'
  145. picname = ip + '-' + name +'.png'
  146. pic_save_path = os.path.join(pic_save_path_dir,picname)
  147. file=open(pic_save_path,'wb')
  148. file.write(data)
  149. #file.flush()
  150. file.close()
  151.  
  152. #多线程并发调用该函数
  153. def pic_save_th(ip):
  154. #根据ip获取hostid
  155. host_data = get_hostid(ip)
  156. host_result = Http_access(host_data)
  157. if host_result is not None: #判断该IP是否在zabbix中存在
  158. hostid = host_result['hostid']
  159.  
  160. #根据监视器名称获取相应的itemid
  161. cpuname = 'CPU Usage'
  162. memoryname = 'Memory - Memory available'
  163. diskname = 'Disk - Current Disk Queue Length'
  164. netcard = 'Traffic for Public Receive'
  165. item_cpu = get_itemid(hostid,cpuname)
  166. item_memory = get_itemid(hostid,memoryname)
  167. item_disk = get_itemid(hostid,diskname)
  168. item_netcard = get_itemid(hostid,netcard)
  169.  
  170. itemid_cpu = Http_access(item_cpu)['itemid']
  171. itemid_memory = Http_access(item_memory)['itemid']
  172. itemid_disk = Http_access(item_disk)['itemid']
  173. itemid_netcard = Http_access(item_netcard)['itemid']
  174.  
  175. #根据itemid获取相应的graphid
  176. graphdata_cpu = get_graphid(itemid_cpu)
  177. graphdata_memory = get_graphid(itemid_memory)
  178. graphdata_disk = get_graphid(itemid_disk)
  179. graphdata_netcard = get_graphid(itemid_netcard)
  180.  
  181. graphid_cpu = Http_access(graphdata_cpu)['graphid']
  182. graphid_memory = Http_access(graphdata_memory)['graphid']
  183. graphid_disk = Http_access(graphdata_disk)['graphid']
  184. graphid_netcard = Http_access(graphdata_netcard)['graphid']
  185.  
  186. print ip#,graphid_cpu,graphid_memory,graphid_disk,graphid_netcard
  187.  
  188. #调用pic_save函数保存图片到本地
  189. pic_save(ip,cpuname,graphid_cpu)
  190. pic_save(ip,memoryname,graphid_memory)
  191. pic_save(ip,diskname,graphid_disk)
  192. pic_save(ip,netcard,graphid_netcard)
  193. else:
  194. print '%s doesnot exist in zabbix' %ip
  195.  
  196. #定义线程数控制函数,num表示每次并发的线程数
  197. def lstg(num,lst):
  198. #定义每段的个数num
  199. l = len(lst)
  200. g = l/num #取分成几组
  201. last = l%num #判断是否有剩余的数
  202. lstn = []
  203. if num >= l:
  204. lstn.append(lst)
  205. else:
  206. for i in range(g):
  207. i=i+1
  208. n=i*num
  209. m=n-num
  210. lstn.append(lst[m:n])
  211.  
  212. if last <> 0:
  213. lstn.append(lst[-last:])
  214. return lstn
  215.  
  216. # serverip=['10.160.26.30','10.160.26.31','10.160.26.32']
  217. # for ip in serverip:
  218. # pic_save_th(ip)
  219.  
  220. if __name__ =='__main__':
  221. #定义线程数量
  222. tnum = 5
  223. 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']
  224. for ips in lstg(tnum,serverips):
  225. threads=[]
  226. for ip in ips:
  227. #创建并启动进程
  228. t = threading.Thread(target=pic_save_th,args=(ip,))
  229. #t.setName('th-'+ ip)
  230. t.setDaemon(True)
  231. t.start()
  232. threads.append(t)
  233. #等待每个线程结束
  234. for t in threads:
  235. #print t.name,t.is_alive(),ctime()
  236. t.join()

Python抓取zabbix性能监控图的更多相关文章

  1. python抓取zabbix图形,并发送邮件

    最近十九大非常烦,作为政府网站维护人员,简直是夜不能寐.各种局子看着你,内保局,公安部,360,天融信,华胜天成,中央工委,政治委员会... 360人员很傻X,作为安全公司,竟然不能抓到XX网站流量, ...

  2. python抓取不得姐动图(报错 urllib.error.HTTPError: HTTP Error 403: Forbidden)

    抓取不得姐动图(报错) # -*- coding:utf-8 -*- #__author__ :kusy #__content__:文件说明 #__date__:2018/7/23 17:01 imp ...

  3. python抓取性感尤物美女图

    由于是只用标准库,装了python3运行本代码就能下载到多多的美女图... 写出代码前面部分的时候,我意识到自己的函数设计错了,强忍继续把代码写完. 测试发现速度一般,200K左右的下载速度,也没有很 ...

  4. Python爬虫之三种网页抓取方法性能比较

    下面我们将介绍三种抓取网页数据的方法,首先是正则表达式,然后是流行的 BeautifulSoup 模块,最后是强大的 lxml 模块. 1. 正则表达式   如果你对正则表达式还不熟悉,或是需要一些提 ...

  5. 如何用python抓取js生成的数据 - SegmentFault

    如何用python抓取js生成的数据 - SegmentFault 如何用python抓取js生成的数据 1赞 踩 收藏 想写一个爬虫,但是需要抓去的的数据是js生成的,在源代码里看不到,要怎么才能抓 ...

  6. 使用Python抓取猫眼近10万条评论并分析

    <一出好戏>讲述人性,使用Python抓取猫眼近10万条评论并分析,一起揭秘“这出好戏”到底如何? 黄渤首次导演的电影<一出好戏>自8月10日在全国上映,至今已有10天,其主演 ...

  7. python抓取知乎热榜

    知乎热榜讨论话题,https://www.zhihu.com/hot,本文用python抓取下来分析 #!/usr/bin/python # -*- coding: UTF-8 -*- from ur ...

  8. Python 抓取网页并提取信息(程序详解)

    最近因项目需要用到python处理网页,因此学习相关知识.下面程序使用python抓取网页并提取信息,具体内容如下: #---------------------------------------- ...

  9. 使用 Python 抓取欧洲足球联赛数据

    Web Scraping在大数据时代,一切都要用数据来说话,大数据处理的过程一般需要经过以下的几个步骤    数据的采集和获取    数据的清洗,抽取,变形和装载    数据的分析,探索和预测    ...

随机推荐

  1. vim中使用系统粘贴板

    在vim中如果想使用系统粘贴板,也就是说,如果你在其他程序中复制内容,那么使用shift+insert组合键就可以粘贴进来. 需要说明的是,vim中的粘贴板有很多,你可以输入 :reg来进行查看.而我 ...

  2. Python中创建守护进程

    python 创建守护进程 python 的os.setdid()提供了类似linux c api的 setsid 也可以通过unix双fork创建守护进程. 几个相关的函数 os.umask(0) ...

  3. zoj 2818 Root of the Problem(数学思维题)

    题目链接: http://acm.zju.edu.cn/onlinejudge/showProblem.do?problemCode=2818 题目描述: Given positive integer ...

  4. 从Spring-Session源码看Session机制的实现细节

    Re:从零开始的Spring Session(一) Re:从零开始的Spring Session(二) Re:从零开始的Spring Session(三) 去年我曾经写过几篇和 Spring Sess ...

  5. (原)SQL Server 代理作业执行持续时间简述

    本文目录列表: 1.SQL Server 代理作业概述2.获取代理作业执行时间方法一 3.获取代理作业执行时间方法二4.总结语 5.参考目录清单列表 正文:   1.SQL Server 代理作业概述 ...

  6. WPF备忘录(5)怎样修改模板中的控件

    首先,想问大家一个问题,你们如果要给一个Button添加背景图片会怎么做?(呵呵,这个问题又点小白哈) 是这样吗? <Button Height="57" Horizonta ...

  7. Springmvx拦截html出现406解决以及Server Tomcat v8.0 Server at localhost failed to start 问题解决方法

    问题是这样的:环境是SSM框架,在配置好的框架里想请求一个html,结果406了,406就是HTTP协议状态码的一种,表示无法使用请求的特性来响应请求的网页.一般指客户端浏览器不接受所请求页面的MIM ...

  8. Spring全家桶系列–[SpringBoot入门到跑路]

    //本文作者:cuifuan Spring全家桶————[SpringBoot入门到跑路] 对于之前的Spring框架的使用,各种配置文件XML.properties一旦出错之后错误难寻,这也是为什么 ...

  9. POJ3281(KB11-B 最大流)

    Dining Time Limit: 2000MS   Memory Limit: 65536K Total Submissions: 19170   Accepted: 8554 Descripti ...

  10. js-权威指南学习笔记19

    第十九章 jQuery类库 1.传递HTML文本字符串给$()方法,jQuery会根据传入的文本创建好HTML元素并封装为jQuery对象返回. 2.想要遍历jQuery对象中的所有元素时,可以调用e ...