本文共 1192 字,大约阅读时间需要 3 分钟。
下面是代码片段,写得比较简陋,基本想法就是使用os.popen方法执行一段命令脚本mysql -uroot -padmin -e "show full processlist;"(不太好的一点是这里写了root用户的密码,比较危险),然后逐行扫描,将带有SQL关键字的行,写入文本文件,文本文件按照当前的时间保存。
# -*- coding: utf-8 -*-
import os
import codecs
import datetime
if __name__ == "__main__":
cmd = 'mysql -uroot -padmin -e "show full processlist;"'
fd = os.popen(cmd)
content = []
for line in fd:
lower_line = line.lower()
if lower_line.find('select') != -1 or (lower_line.find('update') != -1 and lower_line.find('table') != -1) or lower_line.find('insert') != -1 or lower_line.find('delete') != -1 or lower_line.find('create') != -1 or lower_line.find('alter') != -1 or lower_line.find('drop') != -1 or lower_line.find('truncate') != -1:
content.append(line.strip())
fd.close()
now = str(datetime.datetime.now())
p = now.index('.')
now = now[:p]
now = now.replace('-','').replace(':','').replace(' ','')
try:
os.mkdir('/root/mysqlprocesslist/')
except Exception:
print '/root/mysqlprocesslist/ folder alreay exist, no need to create'
if len(content) > 0:
fw = codecs.open('/root/mysqlprocesslist/'+now, 'w', 'utf-8')
for c in content:
fw.write(c+'\n')
fw.close()
写完这个脚本后,在/etc/crontab中,写上
*/1 * * * * root python py_cmd.py
就可以每分钟监视了。
转载地址:http://hxowx.baihongyu.com/