一、功能说明

二、代码详情

1、通过阿里sdk获取慢查询列表,格式化。

2、企业微信报警接口

3、deamon
#!/usr/bin/python
#-*- conding:utf-8 -*-
from aliyunsdkcore.client import AcsClient
from aliyunsdkrds.request.v20140815 import DescribeDBInstanceAttributeRequest
from aliyunsdkrds.request.v20140815 import DescribeSlowLogRecordsRequest
import requests
import json
import os
import time
import logging
import subprocess
#ali key
client = AcsClient(
"",
"",
""
);
log_file = "/tmp/rdsslowinfo.log"
logging.basicConfig(filename=log_file,filemode='a',level=logging.DEBUG) def WARNING(*objs):
print("[%s] : " % time.strftime("%y-%m-%d %H:%M:%S", time.localtime()), *objs, file=sys.stderr) class rdsInfo(object):
''' ali rds slow log get'''
def __init__(self,dbId,startTime,endTime):
self.dbId = dbId
self.startTime = startTime
self.endTime = endTime def slowlogGet(self):
request = DescribeSlowLogRecordsRequest.DescribeSlowLogRecordsRequest()
request.set_accept_format('json')
request.set_DBInstanceId(self.dbId)
request.set_StartTime(self.startTime)
request.set_EndTime(self.endTime)
response = client.do_action_with_exception(request)
data = json.loads(response)
return data def instanceGet(self):
request = DescribeDBInstanceAttributeRequest.DescribeDBInstanceAttributeRequest()
request.set_accept_format('json')
request.set_DBInstanceId(self.dbId)
response = client.do_action_with_exception(request)
data = json.loads(response)
#print (data['Items'])
return data class WeChat:
'''微信接口'''
def __init__(self,user):
self.CORPID = '' #企业ID, 登陆企业微信,在我的企业-->企业信息里查看
self.CORPSECRET = '' #自建应用,每个自建应用里都有单独的secret
self.AGENTID = '' #应用代码
self.TOUSER = user # 接收者用户名, @all 全体成员 def _get_access_token(self):
url = 'https://qyapi.weixin.qq.com/cgi-bin/gettoken'
values = {'corpid': self.CORPID,
'corpsecret': self.CORPSECRET,
}
req = requests.post(url, params=values)
data = json.loads(req.text)
# print (data)
return data["access_token"] def get_access_token(self):
try:
with open('access_token.conf', 'r') as f:
t, access_token = f.read().split()
except:
with open('access_token.conf', 'w') as f:
access_token = self._get_access_token()
cur_time = time.time()
f.write('\t'.join([str(cur_time), access_token]))
return access_token
else:
cur_time = time.time()
if 0 < cur_time - float(t) < 7200: #token的有效时间7200s
return access_token
else:
with open('access_token.conf', 'w') as f:
access_token = self._get_access_token()
f.write('\t'.join([str(cur_time), access_token]))
return access_token def send_data(self, msg):
send_url = 'https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=' + self.get_access_token()
send_values = {
"touser": self.TOUSER,
"msgtype": "text",
"agentid": self.AGENTID,
"text": {
"content": msg
},
"safe": ""
}
send_msges=(bytes(json.dumps(send_values), 'utf-8'))
respone = requests.post(send_url, send_msges)
respone = respone.json()#当返回的数据是json串的时候直接用.json即可将respone转换成字典
# print (respone["errmsg"])
return respone["errmsg"] def dataInit():
''' get data info'''
instanceInfo = {
'rm-阿里域名':'业务线',
'rm-':'',
'rm-':'',
'rm-':'',
'rm-':'',
}
alarmList = ['','','','','']#收报警人列表
for dbUrl in instanceInfo.keys():
nowTime = time.strftime("%Y-%m-%dT%H:%MZ")
second = time.time() - 24*60*60 #查询间隔 自己定义
tago = time.strftime('%Y-%m-%dT%H:%MZ', time.localtime(second))
rdsinfo = rdsInfo(dbUrl,tago,nowTime)
slowlog_data = rdsinfo.slowlogGet()
instance_data = rdsinfo.instanceGet()
try:
for recode in slowlog_data['Items']['SQLSlowRecord']:
#print(recode)
ParseRowCounts = recode['ParseRowCounts']
ReturnRowCounts = recode['ReturnRowCounts']
QueryTimes = recode['QueryTimes']
HostAddress = recode['HostAddress']
LockTimes = recode['LockTimes']
ExecutionStartTime = recode['ExecutionStartTime']
SQLText = recode['SQLText']
DBName = recode['DBName']
content = '''
业务线 :{url}
SQL来源:{HostAddress}
执行时间:{ExecutionStartTime}
数据库名:{DBName}
执行时长:{QueryTimes}
锁定时长:{LockTimes}
解析行数:{ParseRowCounts}
返回行数:{ReturnRowCounts}
SQL详情:{SQLText}
''' .format(url=instanceInfo[dbUrl],HostAddress=HostAddress,ExecutionStartTime\
=ExecutionStartTime,DBName=DBName,QueryTimes=QueryTimes,LockTimes=LockTimes,\
ParseRowCounts=ParseRowCounts,ReturnRowCounts=ReturnRowCounts,SQLText=SQLText)
#print(content)
logging.info(content)
for alarm in alarmList:
wx = WeChat(alarm)
wx.send_data(msg=content)
except Exception as e:
WARNING('[%s]')%(e)
class Daemon:
''' Daemon '''
def createDaemon(self):
try:
if os.fork() > 0: os._exit(0) # exit father…
except OSError as error:
print ('fork #1 failed: %d (%s)' % (error.errno, error.strerror))
os._exit(1)
# it separates the son from the father
os.chdir('/')
os.setsid()
os.umask(0)
# create - fork 2
try:
pid = os.fork()
if pid > 0:
print ('Daemon PID %d' % pid)
logging.info('Daemon PID %d' % pid)
os._exit(0)
except OSError as error:
print ('fork #2 failed: %d (%s)' % (error.errno, error.strerror))
os._exit(1)
self.run() # function demo def run(self):
while True:
dataInit()
time.sleep(24*60*60) #deamon运行间隔时间
#time.sleep(5)
#except Exception,e:
# traceback.print_exc() if __name__ == '__main__':
daemon = Daemon()
daemon.createDaemon()

Python3 获取RDS slowlog+微信接口报警的更多相关文章

  1. java微信接口之五—消息分组群发

    一.微信消息分组群发接口简介 1.请求:该请求是使用post提交地址为: https://api.weixin.qq.com/cgi-bin/message/mass/sendall?access_t ...

  2. java微信接口之四—上传素材

    一.微信上传素材接口简介 1.请求:该请求是使用post提交地址为: https://api.weixin.qq.com/cgi-bin/media/uploadnews?access_token=A ...

  3. java微信接口之三—上传多媒体文件

    一.微信上传多媒体接口简介 1.请求:该请求是使用post提交from来实现的,我们可以在网页上进行表单提交来实现.地址为: http://file.api.weixin.qq.com/cgi-bin ...

  4. java微信接口之二—获取用户组

    一.微信获取用户组接口简介 1.请求 该请求也是GET方式请求.请求的url格式如下: https://api.weixin.qq.com/cgi-bin/groups/get?access_toke ...

  5. 微信接口开发1--向微信发送请求--获取access_token

    //随便放置一个php文件在服务器上.执行该方法--调用模拟get提交---到微信-->获得微信返回的access_token 不建议自己编写模拟get提交方法. 建议直接导入微信框架LaneW ...

  6. zabbix 定义触发器,并使用邮件,微信消息报警。

    触发器可根据监控项获取到的值来进行一些操作,如监控项获取到的values为0,触发器可判断为正常,如果获取到了1,就触发报警. 定义报警方式比较简单,但是用shell脚本实现起来,总是有格式问题,所以 ...

  7. C#开发微信门户及应用(1)--开始使用微信接口

    微信应用如火如荼,很多公司都希望搭上信息快车,这个是一个商机,也是一个技术的方向,因此,有空研究下.学习下微信的相关开发,也就成为日常计划的重要事情之一了.本系列文章希望从一个循序渐进的角度上,全面介 ...

  8. C#开发微信门户及应用(42)--使用Autofac实现微信接口处理的控制反转处理

    在很多情况下,我们利用IOC控制反转可以很方便实现一些接口的适配处理,可以在需要的时候切换不同的接口实现,使用这种方式在调用的时候,只需要知道相应的接口接口,具体调用哪个实现类,可以在配置文件中动态指 ...

  9. 练习题(登陆-进度条-微信接口判断qq-微信接口判断列车时刻表-)

    1.写一个用户的登陆注册的界面,用户的密码用hashlib加密存在文件中,登陆时候,用户的密码要和文件中的密码一致才行 def sha(password): #加密函数 passwd = hashli ...

随机推荐

  1. 在Mac和win7上分别安装了docker后,发现原来的vagrant都启动不了了

    在Mac和win7上分别安装了docker后,发现原来的vagrant都启动不了了 liugx@liugx vagrant$ vagrant up /opt/vagrant/embedded/gems ...

  2. mysql大数据量之limit优化

    背景:当数据库里面的数据达到几百万条上千万条的时候,如果要分页的时候(不过一般分页不会有这么多),如果业务要求这么做那我们需要如何解决呢?我用的本地一个自己生产的一张表有五百多万的表,来进行测试,表名 ...

  3. appium+python自动化31-android_uiautomator定位

    前言 appium就是封装android的uiautomator这个框架来的,所以uiautomator的一些定位方法也可以用 text 1.通过text文本定位语法 new UiSelector() ...

  4. appium+python自动化30-list定位(find_elements)

    前言 有时候页面上没有id属性,并且其它的属性不唯一,平常用的比较多的是单数(element)的定位方法,遇到元素属性不唯一,就无法直接定位到了. 于是我们可以通过复数(elements)定位,先定位 ...

  5. springmvc和activemq的整合使用

    1.简介:ActiveMQ 是Apache出品,最流行的,能力强劲的开源消息总线.ActiveMQ 是一个完全支持JMS1.1和J2EE 1.4规范的 JMS Provider实现,尽管JMS规范出台 ...

  6. click 模块使用方法说明

    !/usr/bin/env python -- coding: utf-8 -- import click @click.command() @click.option('--count', defa ...

  7. node中的require

    /*在node中,可以使用require()函数来加载模块. * require函数使用一个参数,参数值可以带有完整路径的模块的文件名,也可以为模块名.当使用node中提供的模块时,在require函 ...

  8. windows zabbix_agent 客户端安装部署

    1.下载客户端:zabbix_agentd.zip 2.在c盘创建文件夹zabbix,解压conf和bin目录 3.将conf下的zabbix_agentd.win.conf 修改为zabbix_ag ...

  9. 数据库DRDS中间件介绍

    DRDS/TDDL alibaba. Distributed Relational Database Service. 阿里分布式数据库DRDS的前身是淘宝分布式数据库层TDDL,大概在2012年的时 ...

  10. SVN目录结构

    整理了一下svn目录结构,如下: 项目名称 ----branches    软件产品的迭代开发版本 ----tags        软件产品经过完整测试的历史稳定版本,已部署在客户机器上使用的 --- ...