Prometheus api 获取监控数据导出 CSV

1、 发送给企业微信机器人

#  upload_file 是为了生成 media_id, 供消息使用

# -*- encoding: utf-8 -*-
import requests, paramiko, json, os, datetime
import pandas as pd
from copy import copy
from urllib3 import encode_multipart_formdatadef upload_file(file_path, wx_upload_url):file_name = file_path.split("/")[-1]with open(file_path, 'rb') as f:length = os.path.getsize(file_path)data = f.read()headers = {"Content-Type": "application/octet-stream"}params = {"filename": file_name,"filelength": length,}file_data = copy(params)file_data['file'] = (file_path.split('/')[-1:][0], data)encode_data = encode_multipart_formdata(file_data)file_data = encode_data[0]headers['Content-Type'] = encode_data[1]r = requests.post(wx_upload_url, data=file_data, headers=headers)print(r.text)media_id = r.json()['media_id']return media_id

# media_id 通过上一步上传的方法获得

def qi_ye_wei_xin_file(wx_url, media_id):headers = {"Content-Type": "text/plain"}data = {"msgtype": "file","file": {"media_id": media_id}}r = requests.post(url=wx_url,headers=headers, json=data)print(r.text)

2、 从Prometheus 上获取监控数据

# 得到一个Overssh的返回值
def get_file_list(hostname, port, username, key_name, command):ssh = paramiko.SSHClient()  # 创建SSH对象ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())  # 允许连接不在know_hosts文件中的主机# ssh.connect(hostname='xxx.xxx.xxx.xxx', port=22, username='root', password='xxx')  # 连接服务器ssh.connect(hostname=hostname, port=port, username=username,pkey=paramiko.RSAKey.from_private_key_file(key_name))  # 连接服务器stdin, stdout, stderr = ssh.exec_command(command)file_list = str(stdout.read(), encoding="utf-8")ssh.close()  # 关闭连接return file_list

3、将PD写入到磁盘

def write_to_dish(results,fileDir):writer = pd.ExcelWriter(fileDir)results.to_excel(writer,float_format='%.5f')writer.save()

4、定义好需要查询的metric

# 查询需要检查的数据,第一个必须为 up
def rds_metrics_list():return {'up': '状态','rds001_cpu_util': 'CPU使用率(%)','rds002_mem_util': '内存使用率(%)','rds003_iops': 'iops','rds004_bytes_in': '网络流量入(Bytes)','rds005_bytes_out': '网络流量出(Bytes)','rds008_qps': 'QPS','rds009_tps': 'TPS','rds081_vm_ioutils': 'io使用率(%)','rds047_disk_total_size': '磁盘总大小(G)','rds048_disk_used_size': '磁盘使用(G)','mysql_global_status_threads_connected': '当前连接数','mysql_global_variables_max_connections': '最大连接数',}

5、Prometheus 获取数据落盘数据,并发送给企业微信机器人

if __name__ == '__main__':# prometheus 主机信息host_info = {'hostname': 'xxx.xxx.xxx.xxx', 'port': 22, 'username': 'root', 'key_name': './keys/xxx'}# 检查文件路径check_file_dir = 'check_files'# 检查文件时间,时区问题需要减去8小时curhour = -17  # 默认给-17 当前时间是-8.1# 检查项目 为job名prometheus 中的job, name 为项目的巡检名字, robot_key 为企业微信机器人check_file_dict = {'job': {'name': 'name', 'value': [], 'key': 'xxx','robot_key': 'xxx'}}if not os.path.exists(check_file_dir):os.makedirs(check_file_dir)metrics_list = rds_metrics_list()check_time_day = (datetime.datetime.now() + datetime.timedelta(hours=curhour)).strftime("%Y-%m-%d")check_time_hour = (datetime.datetime.now() + datetime.timedelta(hours=curhour)).strftime("%H:%M")print(check_time_day, check_time_hour)for metric in metrics_list:command = 'curl http://127.0.0.1:9090/api/v1/query_range?query=%s\&start=%sT%s:00Z\&end=%sT%s:15Z\&step=15s' \%(metric, check_time_day, check_time_hour, check_time_day, check_time_hour)file_list = get_file_list(host_info['hostname'], host_info['port'], host_info['username'], host_info['key_name'], command)metrics = json.loads(file_list)for key in metrics['data']['result']:# Mysql数据库巡检Prometheus_job = key['metric']['job']Prometheus_instance = key['metric']['instance']for project in check_file_dict:if Prometheus_job == project and key['metric']['__name__'] == 'up':metric_dict = {}metric_dict['instance'] = key['metric']['instance']metric_dict[metrics_list[metric]] = key['values'][0][1]check_file_dict[key['metric']['job']]['value'].append(metric_dict)# print(check_file_dict)for instance in check_file_dict[project]['value']:if key['metric']['job'] == check_file_dict[project]['key'] and key['metric']['instance'] == instance['instance']:instance[metrics_list[metric]] = key['values'][0][1]for key in check_file_dict:test_report = './'+check_file_dir+'/'+check_file_dict[key]['name']+'_'+check_time_day+'.xlsx'print(test_report)if os.path.exists(test_report):os.remove(test_report)print(check_file_dict[key]['value'])write_to_dish(pd.DataFrame(check_file_dict[key]['value']),fileDir=test_report)#发送企业微信机器人wx_api_key = check_file_dict[key]['robot_key']  # 这个地方写你自己的keywx_upload_url = "https://qyapi.weixin.qq.com/cgi-bin/webhook/upload_media?key={}&type=file".format(wx_api_key)wx_url = 'https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key={}'.format(wx_api_key)media_id = upload_file(test_report, wx_upload_url)qi_ye_wei_xin_file(wx_url, media_id)

6、最终群组里面收到机器巡检文件

Prometheus api 查询监控数据导出 CSVExcel相关推荐

  1. Prometheus运维二 安装部署Prometheus及使用PromQL查询监控数据

    1,安装部署. 1,环境准备. 软件包下载地址:https://prometheus.io/download/ 地址 规划/软件包 192.168.0.10 Prometheus Server 192 ...

  2. 使用聚合数据API查询快递数据-短信验证码-企业核名

    有位朋友让我给他新开的网站帮忙做几个小功能,如下: 输入快递公司.快递单号,查询出这个快件的所有动态(从哪里出发,到了哪里) 在注册.登录等场景下的手机验证码(要求有一定的防刷策略) 通过输入公司名的 ...

  3. beeline 将查询的数据导出来_滴滴大数据安全权限实践

    导读: 在滴滴,数据是非常重要的资产,基于数据的数仓建设,数据分析.数据挖掘.数据科学等构建了滴滴的数据体系,支撑着滴滴的业务快速发展.在这个背景下,如何保障用户获取数据的易用性的同时可以更加安全,是 ...

  4. zabbix数据导出表格_zabbix监控数据导出

    zabbix服务器迁移 单位有个zabbix监控服务器,zabbix是1.6稳定版.最近需要迁移到别的服务器上,要求原来的数据都不能丢失,迁移过来后zabbix服务能正常继续监控.这个问题中的关键是数 ...

  5. zabbix数据导出表格_zabbix 监控数据导出

    zabbix服务器迁移 单位有个zabbix监控服务器,zabbix是1.6稳定版.最近需要迁移到别的服务器上,要求原来的数据都不能丢失,迁移过来后zabbix服务能正常继续监控.这个问题中的关键是数 ...

  6. 数据库查询的数据导出到xls表,集合数据导出到xls表

    //实体类package com.outxls;public class Student {private Integer studentId;private String studentName;p ...

  7. python 查询mysql数据导出excl_python查询mysql并生成excel表

    需求说明 开发不愿意单独为某个项目做后台 并且运营那边需要合并多个表的数据 因此找上了我. 要求每周执行一次.月初也执行一次 要查询2个mysql数据库多个表并生成excel表 我的想法 找开发要sq ...

  8. 扩展 Geocoder 调用高德API查询POI数据

    Geocoder 是一个非常简单的控件,但也是非常常用且实用的控件,顾名思义,Geocoder 就是地理编码的意思,而平常我们经常会查询一些地物,也就是常用的 POI 搜索,就是 Geocoder 的 ...

  9. 【DevOps】推荐Go语言开源项目:Excelize ,获取阿里云ECS实例监控数据导出到自定义Excel表格(三)

    目录 愿你前行的路上终有人陪

最新文章

  1. 1. vi 与 vim 有什么区别呢,它们之间有什么关系?
  2. 本地文件与服务器传输,云服务器 与本地文件传输
  3. 模拟alert,confirm,prompt
  4. 使用IDEA创建一个Servlet应用程序
  5. Java 类在 Tomcat 中是如何加载的?
  6. C++类分号(;)问题
  7. 多线程写图像文件的一点小测试
  8. Confluence 6 重新获得附件指南
  9. three.js 文本_使用Three-bmfont-text在Three.js中创建文本
  10. 《Using OpenRefine》翻译~17
  11. bat运行Java程序
  12. NJM4556AM集成电路是高增益、大输出电流双路运算放大器
  13. android 进入recovery,安卓手机如何进入Recovery模式的通用方式详解
  14. springboot接入支付宝支付
  15. keytool 错误:Keystore was tampered with, or password was incorrect
  16. RenderMonkey基本使用方法【转】
  17. 苹果平板id怎么注册_怎么做成苹果笔记?苹果平板怎么做笔记? - 敬业签便签...
  18. python分析股票数据 彤_Python数据分析:股票数据
  19. IP协议,ARP协议
  20. SQLSTATE[HY000]: General error: 1449 The user specified as a definer (‘root‘@‘%‘) does not exist

热门文章

  1. ERROR: cannot launch node of type [map_server/map_server]: map_server
  2. [附源码]计算机毕业设计Python高血压分析平台(程序+源码+LW文档)
  3. 华为数通笔记-MAC地址
  4. 秋招面试题“背”好了,那简历呢?
  5. php做网站步骤_新手如何用PHP开发一个完整的网站?
  6. MySQL学习笔记-恶补基础篇
  7. 有关于中通公司需要提交的面试题答案
  8. pinpoint2.3.3安装和部署
  9. 关于俄罗斯方块游戏软件C语言初步感受
  10. 避开这四个雷区,你也可以策划出10万+创意素材! | 黎想