Python監視MySQL正在運行的SQL

下面是代碼片斷,寫得比較簡陋,基本想法就是使用os.popen方法執行一段命令腳本mysql -uroot -padmin -e "show full processlist;"(不太好的一點是這裏寫了root用戶的密碼,比較危險),而後逐行掃描,將帶有SQL關鍵字的行,寫入文本文件,文本文件按照當前的時間保存。python

# -*- 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中,寫上mysql

*/1 * * * * root python py_cmd.py

就能夠每分鐘監視了。sql

相關文章
相關標籤/搜索