python MySQL慢查询监控
MySQL慢查询会话监控
#!/usr/bin/python
# -*- coding: UTF-8 -*-
from email.mime.text import MIMEText
from email.utils import formataddr
from email.mime.multipart import MIMEMultipart
import MySQLdb
import smtplib
import datetime
import logging
import logging.handlers
import os
def handlemysql(sql):
"""
执行sql
"""
db = MySQLdb.connect(host, user, passwd, dbname)
cursor = db.cursor()
monitor_log(sql)
cursor.execute(sql)
data = cursor.fetchall()
# 关闭数据库连接
db.close()
return data
def execsql(num):
"""
查询进程id
:return:
"""
num = int(num[0][1])
process_id_sql = "SELECT id FROM information_schema.processlist WHERE command not in ('Connect','Sleep','Binlog Dump') and time >= %d and user not in ('wedba','replicator','root','system user')"
# process_id_sql = "SELECT id FROM information_schema.processlist WHERE time >= %d and user not in ('wedba','replicator','system user')"
if 50 < num < 100:
sql = process_id_sql % 60
ret = handlemysql(sql)
return ret
elif 100 < num < 200:
sql = process_id_sql % 30
ret = handlemysql(sql)
return ret
elif 200 < num:
sql = process_id_sql % 10
ret = handlemysql(sql)
return ret
else:
loginfo = "Not need to kill threads"
monitor_log(loginfo)
exit()
def killid(pid):
"""
kill 进程id
:param arg:
:return:
"""
sendsql = "select user,host,db,command,time,info from information_schema.processlist where command not in ('sleep') and user not in ('wedba') order by time desc"
# sendsql = "select user,host,db,command,time,info from information_schema.processlist"
if pid:
content = handlemysql(sendsql)
for i in pid:
i = long(i[0])
killsql = "kill %d" % i
handlemysql(killsql)
msg = ""
for item in content:
if item:
msg = msg + "<p>" + ",".join(str(line) for line in item) + "</p>\n"
with open("/tmp/info.html", 'w+') as f:
f.write(msg)
monitor_log("write /tmp/info.html success")
def senmail(emailuser, emailpwd, tousers):
"""
发邮件功能
:param name:
:param mailaddr:
:param title:
:param content:
:return:
"""
msg = MIMEMultipart()
msg['From'] = formataddr(["monitor", emailuser])
msg['To'] = formataddr([tousers[0], tousers[0]])
msg['Subject'] = "业务从库数据库会话监控"
mail_msg = "业务从库数据库kill会话sql详情"
msg.attach(MIMEText(mail_msg, 'plain', 'utf-8'))
# ---这是附件部分---
att1 = MIMEText(open('/tmp/info.html', 'rb').read(), 'base64', 'utf-8')
att1["Content-Type"] = 'application/octet-stream'
att1["Content-Disposition"] = 'attachment; filename="info.html"'
msg.attach(att1)
try:
# 创建SMTP对象
server = smtplib.SMTP_SSL("smtp.exmail.qq.com", 465)
# server.set_debuglevel(1)
server.login(emailuser, emailpwd)
server.sendmail(emailuser, tousers, msg.as_string())
server.quit()
os.rename('/tmp/info.html','/tmp/info.html%s' % datetime.datetime.now())
print u"%s\t邮件发送成功!" % datetime.datetime.now()
monitor_log("Send mail success!")
except smtplib.SMTPException:
print u"Error: 无法发送邮件"
monitor_log("Error: Send mail faild")
def monitor_log(loginfo, logfile="/tmp/monitor_mysql.log"):
"""
log记录
:return:
"""
LOG_FILE = logfile
handler = logging.handlers.RotatingFileHandler(LOG_FILE, maxBytes=10 * 1024 * 1024, backupCount=5)
fmt = '%(asctime)s - %(filename)s:%(lineno)s - %(name)s - %(message)s'
formatter = logging.Formatter(fmt)
handler.setFormatter(formatter)
logger = logging.getLogger('monitor-mysql')
if not len(logger.handlers):
logger.addHandler(handler)
logger.setLevel(logging.INFO)
logger.info(loginfo)
if __name__ == '__main__':
host = "192.168.1.100"
user = "root"
passwd = "admin123"
dbname = "information_schema"
emailuser = "shuke@163.com"
emailpwd = "123456"
tousers = ['Tome@163.com']
select_threads_sql = "show global status like 'Threads_running'"
num = handlemysql(select_threads_sql)
pid = execsql(num)
if pid:
centent = killid(pid)
senmail(emailuser, emailpwd, tousers)
python MySQL慢查询监控的更多相关文章
- Python + MySQL 批量查询百度收录
做SEO的同学,经常会遇到几百或几千个站点,然后对于收录情况去做分析的情况 那么多余常用的一些工具在面对几千个站点需要去做收录分析的时候,那么就显得不是很合适. 在此特意分享给大家一个批量查询百度收录 ...
- python mysql参数化查询防sql注入
一.写法 cursor.execute('insert into user (name,password) value (?,?)',(name,password)) 或者 cursor.execut ...
- Python MySQL - 创建/查询/删除数据库
#coding=utf-8 import mysql.connector import importlib import sys #连接数据库的信息 mydb = mysql.connector.co ...
- mysql慢查询监控及sql优化
在my.ini添加如下代码,即可查看那个sql语句执行慢了 log-slow-queries = d:/log/mysql-slow.log long_query_time = 1 打开日志 log ...
- MySql 缓存查询原理与缓存监控 和 索引监控
MySql缓存查询原理与缓存监控 And 索引监控 by:授客 QQ:1033553122 查询缓存 1.查询缓存操作原理 mysql执行查询语句之前,把查询语句同查询缓存中的语句进行比较,且是按字节 ...
- python进阶09 MySQL高级查询
python进阶09 MySQL高级查询 一.筛选条件 # 比较运算符 # 等于:= 不等于:!= 或<> 大于:> 小于:< 大于等于>= 小于等于:<= #空: ...
- 10分钟教你Python+MySQL数据库操作
欲直接下载代码文件,关注我们的公众号哦!查看历史消息即可! 本文介绍如何利用python来对MySQL数据库进行操作,本文将主要从以下几个方面展开介绍: 1.数据库介绍 2.MySQL数据库安装和设置 ...
- 【0.2】【MySQL】常用监控指标及监控方法(转)
[MySQL]常用监控指标及监控方法 转自:https://www.cnblogs.com/wwcom123/p/10759494.html 对之前生产中使用过的MySQL数据库监控指标做个小结. ...
- Python之路-python(mysql介绍和安装、pymysql、ORM sqlachemy)
本节内容 1.数据库介绍 2.mysql管理 3.mysql数据类型 4.常用mysql命令 创建数据库 外键 增删改查表 5.事务 6.索引 7.python 操作mysql 8.ORM sqlac ...
随机推荐
- 洛谷 P5108 仰望半月的夜空 解题报告
P5108 仰望半月的夜空 题目描述 半月的夜空中,寄托了多少人与人之间的思念啊 曦月知道,这些思念会汇集成一个字符串\(S(n = |S|)\) 由于思念汇集的过于复杂,因此曦月希望提炼出所有的思念 ...
- CF1012C Hills
显然的DP是,dp[i][j][val] val是1e6的 简化 发现,其实决策很有限,最优解的i-1的val选择有限 题解 这里的一个trick是,f[i][j][0]转移不考虑a[i]和a[i-1 ...
- javaWeb接口开发
链接:http://blog.csdn.net/zxw136511485/article/details/51437115
- php session 登录退出验证
login.html 负责收集用户填写的登录信息 <html><head><title></title></head><body> ...
- bzoj千题计划282:bzoj4517: [Sdoi2016]排列计数
http://www.lydsy.com/JudgeOnline/problem.php?id=4517 组合数+错排公式 #include<cstdio> #include<ios ...
- 通达信zig函数的python实现
通达信zig函数的python实现 代码 # coding: utf-8 """ Created on Sat Jan 05 18:53:39 2019 http://w ...
- MongoDB探索之路(二)——系统设计之CRUD
1.构造实体类 using System; using System.Collections.Generic; using System.Linq; using System.Text; using ...
- [python]文件操作read&readline&readlines
(1)read是将整个文件读入内存,将整个文件的内容当作一个字符串 (2)readline是一行一行的读如内存,每一次读的一行为一个字符串 (3)readlines是一次将整个文件读入内存,但是将整个 ...
- 20155232 2016-2017-3 《Java程序设计》第8周学习总结
20155232 2016-2017-3 <Java程序设计>第8周学习总结 教材学习内容总结 第十四章NIO与NIO2 NIO使用频道来衔接数据结点,在处理数据时,NIO可以让你设定缓冲 ...
- 洛谷 P2089 烤鸡
看了前面大佬的代码,发现这道题的解题思路都大同小异. 首先肯定要定义一个变量累加方案数量,因为方案数量要最先输出,所以所有方案要先储存下来.个人不喜欢太多数组,就只定义一个字符串. 然后我们发现只有1 ...