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. 【CF61D】Eternal Victory

    题目大意:给定一棵 N 个节点的树,求从 1 号节点(根节点)出发,任意节点结束,且至少经过每个节点一次的最短路径是多少. 题解:首先考虑最终要回到根节点的情况,可以发现最短路径长度一定等于该树边权的 ...

  2. 收藏:IPicture总结

    1.IPicture接口对象的创建方法1:直接通过文件创建LPCSTR szFileUrl; IPicture *pIPicture; OleLoadPicturePath(CComBSTR(szFi ...

  3. 关闭ubuntu dash 方法

    因为ubuntu默认的sh是连接到dash的,又因为dash跟bash的不兼容所以出错了.执行时可以把sh换成bash 文件名.sh来执行.成功.dash是什么东西,查了一下,应该也是一种shell, ...

  4. Java基础-线程安全问题汇总

    Java基础-线程安全问题汇总 作者:尹正杰 版权声明:原创作品,谢绝转载!否则将追究法律责任. 一.内存泄漏和内存溢出(out of memory)的区别 1>.什么是内存溢出 答:内存溢出指 ...

  5. SqlParameter防止SQL注入

    SQL注入的解决方案有好几种,待我细细研究过之后逐一讲解. 方法一:SqlParameter方法 这里有一篇博客是详细介绍SqlParameter的,可以看看 点我 string sqlStr=&qu ...

  6. [应用篇]第二篇 JSP自带标签介绍

    JSP 有以下三类标签: 指令:JSP Directive 指令标签用于设置与整个 JSP 页面相关的属性,非常常用. 下面的三种标签是我们使用频率最高的 标签 jsp标签 描述 <%@ pag ...

  7. Linux命令(三)远程登录

  8. 关于Spring mvc注解中的定时任务的配置

    关于spring mvc注解定时任务配置 简单的记载:避免自己忘记,不是很确定我理解的是否正确.有错误地方望请大家指出. 1,定时方法执行配置: (1)在applicationContext.xml中 ...

  9. 线性筛的同时得到欧拉函数 (KuangBin板子)

    线性筛的思想:每个被筛的数是通过它最小的质因子所筛去的. 这种思想保证了每个数只会被筛一次,从而达到线性.并且,这个思想实现起来非常巧妙(见代码注释)! 因为线性筛的操作中用到了倍数的关系去实现,因此 ...

  10. [BZOJ 2257][JSOI2009]瓶子和燃料 题解(GCD)

    [BZOJ 2257][JSOI2009]瓶子和燃料 Description jyy就一直想着尽快回地球,可惜他飞船的燃料不够了. 有一天他又去向火星人要燃料,这次火星人答应了,要jyy用飞船上的瓶子 ...