1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
| import pymysql import os import time os.environ['NLS_LANG']='SIMPLIFIED CHINESE_CHINA.UTF8' command="ps -ef | grep mysql|grep 13306 | 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("127.0.0.1","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()
|