利用Python监控MySQL当前跑的TOP SESSION

Posted robinson1988

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了利用Python监控MySQL当前跑的TOP SESSION相关的知识,希望对你有一定的参考价值。

利用ps命令抓出mysql PID,根据PID再监控每个线程CPU使用率以及跑的SQL语句

import pymysql
import os
import time
os.environ['NLS_LANG']='SIMPLIFIED CHINESE_CHINA.UTF8'
command="ps -ef | grep 3306 | grep -v grep | awk 'print $2'"
with os.popen(command, "r") as pid:
 pid = str(int(pid.read()))
command='top -bi H -p '+ pid +" -n 1 | grep mysql | awk '"+'print '+'$1","$9'+"'"
con=pymysql.connect("192.168.56.10","scott","tiger","db")
cur=con.cursor()
cur.arraysize = 100
sql = "SELECT concat('''',b.USER,'''', '@', '''',b.HOST ,'''',' 在数据库',b.db,' 执行 ',info) info " \\
       "FROM performance_schema.threads a,information_schema.PROCESSLIST b WHERE b.id = a.processlist_id AND a.thread_os_id ="
while True:
 date = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
 with os.popen(command, "r") as p:
   process = p.read()
 if process=='':
     print(str(date)+' System is idle')
 elif process!='':
  line=process.splitlines()
  for rows in line:
     row=rows.split(",")
     cur.execute(sql+row[0])
     for x in cur:
       info = str(x[0])
       print(str(date) + ' ' + info + ' 耗费了'+ row[1] + '% 的CPU')
 time.sleep(3)
cur.close()
con.close()

代码运行示例:

[root@server ~]# python3 monitor.py
2020-05-18 17:15:24 System is idle
2020-05-18 17:15:27 System is idle
2020-05-18 17:15:30 'scott'@'192.168.56.1:59989' 在数据库db 执行 select count(*) from t t1 , t t2 where t1.owner=t2.owner 耗费了99.9% 的CPU
2020-05-18 17:15:34 'scott'@'192.168.56.1:59989' 在数据库db 执行 select count(*) from t t1 , t t2 where t1.owner=t2.owner 耗费了93.8% 的CPU
2020-05-18 17:15:37 'scott'@'192.168.56.1:59989' 在数据库db 执行 select count(*) from t t1 , t t2 where t1.owner=t2.owner 耗费了99.9% 的CPU

 

以上是关于利用Python监控MySQL当前跑的TOP SESSION的主要内容,如果未能解决你的问题,请参考以下文章

利用Python监控Oracle当前跑的TOP SESSION

利用Python监控Oracle当前跑的TOP SESSION

利用Zabbix ODBC monitoring监控MySQL

shell脚本案例利用top命令精确监控cpu使用率

利用mysql时间函数监控表中有没有当天数据

系统监控工具-glances