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慢查询监控的更多相关文章

  1. Python + MySQL 批量查询百度收录

    做SEO的同学,经常会遇到几百或几千个站点,然后对于收录情况去做分析的情况 那么多余常用的一些工具在面对几千个站点需要去做收录分析的时候,那么就显得不是很合适. 在此特意分享给大家一个批量查询百度收录 ...

  2. python mysql参数化查询防sql注入

    一.写法 cursor.execute('insert into user (name,password) value (?,?)',(name,password)) 或者 cursor.execut ...

  3. Python MySQL - 创建/查询/删除数据库

    #coding=utf-8 import mysql.connector import importlib import sys #连接数据库的信息 mydb = mysql.connector.co ...

  4. mysql慢查询监控及sql优化

    在my.ini添加如下代码,即可查看那个sql语句执行慢了 log-slow-queries = d:/log/mysql-slow.log long_query_time = 1 打开日志 log ...

  5. MySql 缓存查询原理与缓存监控 和 索引监控

    MySql缓存查询原理与缓存监控 And 索引监控 by:授客 QQ:1033553122 查询缓存 1.查询缓存操作原理 mysql执行查询语句之前,把查询语句同查询缓存中的语句进行比较,且是按字节 ...

  6. python进阶09 MySQL高级查询

    python进阶09 MySQL高级查询 一.筛选条件 # 比较运算符 # 等于:= 不等于:!= 或<> 大于:> 小于:< 大于等于>= 小于等于:<= #空: ...

  7. 10分钟教你Python+MySQL数据库操作

    欲直接下载代码文件,关注我们的公众号哦!查看历史消息即可! 本文介绍如何利用python来对MySQL数据库进行操作,本文将主要从以下几个方面展开介绍: 1.数据库介绍 2.MySQL数据库安装和设置 ...

  8. 【0.2】【MySQL】常用监控指标及监控方法(转)

    [MySQL]常用监控指标及监控方法 转自:https://www.cnblogs.com/wwcom123/p/10759494.html  对之前生产中使用过的MySQL数据库监控指标做个小结. ...

  9. Python之路-python(mysql介绍和安装、pymysql、ORM sqlachemy)

    本节内容 1.数据库介绍 2.mysql管理 3.mysql数据类型 4.常用mysql命令 创建数据库 外键 增删改查表 5.事务 6.索引 7.python 操作mysql 8.ORM sqlac ...

随机推荐

  1. suoi14 子树查找 (dfs)

    把询问记下来,然后开个桶差分 #include<bits/stdc++.h> #define pa pair<int,int> #define lowb(x) ((x)& ...

  2. SQLServer过期的解决方案

    看图吧,不喜欢说话,图里面我都打备注了 0SQLService异常 1找到安装中心 2升级版本 3监测ing 4输入升级key 5同意并下一步 6下一步 7下一步 8下一步 9收工 10可以打开了

  3. sking

    #include #include #include typedef struct SKI{ int data; int x; int y; char flag; int len; }STSKI; i ...

  4. win7下PLSQL Developer提示“ORA-12154: TNS:无法解析指定的连接标识符”

    解决方法:卸载掉重新安装,注意安装的目录的文件夹不要有特殊的符号,例如64位系统的的安装目录会到Program Files (x86),这时候就会出现"ORA-12154: TNS:无法解析 ...

  5. git clone错误 fatal: early EOF fatal: index-pack failed

    最后用ssh的方式解决了,不用http https://blog.csdn.net/fastjack/article/details/79757520 用了以下的方法还是不行 今天想 clone 一下 ...

  6. 51nod 1258 序列求和 V4

    http://www.51nod.com/onlineJudge/questionCode.html#!problemId=1258 1258 序列求和 V4  基准时间限制:8 秒 空间限制:131 ...

  7. mybatis dao 层开发简易版 非整合 spring

    同样老习惯,先上项目结构截图 首先 补充上篇文中缺失的 mysql demo 用的 小脚本 drop database if exists mybatis; CREATE DATABASE `myba ...

  8. ASP.NET MVC学习(四)之视图View

    1.视图 2.强类型视图 3.@RenderSection("HeaderSection", false)     @RenderBody() 4.子行为 5.ASP.NET MV ...

  9. tclsh 用法

    set foo "a bc" # 定义变量 set b {$a}; # 转义 b的值为" $a " ,而不是变量结果 ; incr a ; # 数字的自增. 将 ...

  10. 原生JS获取元素的位置与尺寸

    1.内高度.内宽度: 内边距 + 内容框 element.clientWidth element.clientHeight 2.外高度,外宽度: 边框 + 内边距 + 内容框 element.offs ...