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

本文介绍了一种利用Python脚本监控MySQL进程的方法,通过获取MySQL的PID,进一步监控每个线程的CPU使用率及正在执行的SQL语句。示例代码展示了如何周期性地读取这些信息,并在系统空闲时输出提示。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

利用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

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值