背景:
關於MySQL的審核的重要性就不說明了,本文的自動化審核是通過Inception和SQLAdvisor實現的,具體的使用可以看它們各自的說明文檔。這里大致介紹下如何部署和使用它們,其實該文章也可以說成是如何在ubuntu下安裝Inception和SQLAdivsor。本文的web平台是通過python的tornado來實現的,詳細信息可以看下面的介紹說明。
環境:
系統:Ubuntu 14.04.5
安裝部署:
1)安裝Inception:
① 下載inception
git clone https://github.com/mysql-inception/inception.git
② 安裝依賴包
1,cmake: sudo apt-get install cmake: 2,libncurses5-dev: sudo apt-get install libncurses5-dev 3,libssl-dev: sudo apt-get install libssl-dev 4,g++ sudo apt-get install g++ 5,m4 sudo apt-get install m4 6,bison:版本最好是2.6之前的,最新的可能會有問題 wget http://ftp.gnu.org/gnu/bison/bison-2.5.1.tar.gz ./configure make make install
做個軟連接:
ln -s /usr/local/inception-master_2.1.50/sql/Inception /usr/bin/Inception
③ 安裝inception
1 安裝,進入clone的目錄執行: sh inception_build.sh debug 上面執行完畢之后再執行,可執行文件在debug下面的sql目錄中,執行: mv debug/ /usr/local/inception-master_2.1.50 2 查看版本: cd /usr/local/inception-master_2.1.50/sql ./Inception -V ./Inception Ver Inception2.1.50 for Linux on x86_64 (Source distribution)
④ 安裝percona-toolkit
wget https://www.percona.com/downloads/percona-toolkit/2.2.20/tarball/percona-toolkit-2.2.20.tar.gz tar zxvf percona-toolkit-2.2.20.tar.gz cd percona-toolkit-2.2.20/ perl Makefile.PL make install
⑤ 測試Inception:
命令行啟動:
Inception --port=6669 2017-03-27 00:45:31 0 [Note] Welcome to use Inception2.1.50 2017-03-27 00:45:31 26811 [Note] Server hostname (bind-address): '*'; port: 6669 2017-03-27 00:45:31 26811 [Note] IPv6 is available. 2017-03-27 00:45:31 26811 [Note] - '::' resolves to '::'; 2017-03-27 00:45:31 26811 [Note] Server socket created on IP: '::'.
參數啟動:可以根據需要來調整參數
Inception --defaults-file=/etc/inception/inc.cnf
各個參數的意義:

[inception] general_log=1 general_log_file=/var/log/inception.log port=6669 socket=/tmp/inc.socket character-set-client-handshake=0 character-set-server=utf8 #備份相關 #需要開啟binlog inception_remote_system_password=cVQ9FLoiTbED2R3ycvnJ inception_remote_system_user=audit_user inception_remote_backup_port=3306 inception_remote_backup_host=192.168.200.49 #在DML語句中沒有WHERE條件時,是不是要報錯 inception_check_dml_where=1 #在DML語句中使用了LIMIT時,是不是要報錯 inception_check_dml_limit=1 #在DML語句中使用了Order By時,是不是要報錯 inception_check_dml_orderby #Select*時是不是要報錯 inception_enable_select_star=1 #order by rand時是不是報錯 inception_enable_orderby_rand=1 #創建或者新增列時如果列為NULL,是不是報錯 inception_enable_nullable=1 #是不是支持外鍵 inception_enable_foreign_key=1 #一個索引中,列的最大個數,超過這個數目則報錯(1-64) inception_max_key_parts=5 #在一個修改語句中,預計影響的最大行數,超過這個數就報錯(1-max) inception_max_update_rows=10000 #一個表中,最大的索引數目,超過這個數則報錯(1-1024) inception_max_keys=16 #建表指定的存儲引擎不為Innodb,不報錯 inception_enable_not_innodb=0 #表示在建表或者建庫時支持的字符集,如果需要多個,則用逗號分隔,影響的范圍是建表、設置會話字符集、修改表字符集屬性等 inception_support_charset=utf8mb4 #建表時,表沒有注釋時報錯 inception_check_table_comment=1 #建表時,列沒有注釋時報錯 inception_check_column_comment=1 #建表時,如果沒有主鍵,則報錯 inception_check_primary_key=1 #是不是支持分區表 inception_enable_partition_table=0 #是不是支持enum,set,bit數據類型 inception_enable_enum_set_bit=0 #是不是要檢查索引名字前綴為"idx_",檢查唯一索引前綴是不是"uniq_" inception_check_index_prefix=1 #自增列是不是要為無符號型 inception_enable_autoincrement_unsigned=1 #當char類型的長度大於這個值時,就提示將其轉換為VARCHAR(1-max) inception_max_char_length=16 #當建表時自增列的值指定的不為1,則報錯 inception_check_autoincrement_init_value=1 #當建表時自增列的類型不為int或者bigint時報錯 inception_check_autoincrement_datatype=1 #建表時,如果沒有為timestamp類型指定默認值,則報錯 inception_check_timestamp_default=0 #允許列自己設置字符集 inception_enable_column_charset=0 #建表時,如果指定的自增列的名字不為ID,則報錯,說明是有意義的,給提示 inception_check_autoincrement_name=1 #在多個改同一個表的語句出現時,報錯,提示合成一個 inception_merge_alter_table=1 #檢查在建表、修改列、新增列時,新的列屬性是不是要有默認值 inception_check_column_default_value=1 #檢查是不是支持BLOB字段,包括建表、修改列、新增列操作 inception_enable_blob_type=1 #檢查在SQL語句中,是不是有標識符被寫成MySQL的關鍵字,默認值為報警。 inception_enable_identifer_keyword=1 #這個參數的作用是為了匹配Python客戶端每次自動設置auto_commit=0的,如果取消則會報錯,針對Inception本身沒有實際意義 #auto_commit=0 #這個參數實際上就是MySQL數據庫原來的參數,因為Incpetion沒有權限驗證過程,那么為了實現更安全的訪問,可以給Inception服務器的這個參數設置某台機器(Inception上層的應用程序)不地址,這樣 #其它非法程序是不可訪問的,那么再加上Inception執行的選項中的用戶名密碼,對MySQL就更加安全 bind_address=127.0.0.1 #inception_user #inception_password #inception_enable_sql_statistic #inception_read_only #打開與關閉Inception對SQL語句中各種名字的檢查,如果設置為ON,則如果發現名字中存在除數字字母下划線之外的字符時,報Identifier "invalidname" is invalid, valid options: [a-z,A-Z,0-9,_]. inception_check_identifier=1 #inception_osc_min_table_size=1 #inception_osc_bin_dir=/data/temp #inception_osc_chunk_time=0.1
Inception需要用MySQL客戶端連接,需要安裝mysql-client,本文測試用Percona MySQL 5.6。因為后面需要用到MySQL,就直接安裝客戶端和服務端:
wget https://repo.percona.com/apt/percona-release_0.1-4.$(lsb_release -sc)_all.deb dpkg -i percona-release_0.1-4.$(lsb_release -sc)_all.deb sudo apt-get update sudo apt-get install percona-server-server-5.6
連接Inception(6669),用inception get variables;測試是否安裝成功。
mysql -uroot -h127.0.0.1 -P6669 Welcome to the MySQL monitor. Commands end with ; or \g. Your MySQL connection id is 2 Server version: Inception2.1.50 1 Copyright (c) 2009-2016 Percona LLC and/or its affiliates Copyright (c) 2000, 2016, Oracle and/or its affiliates. All rights reserved. Oracle is a registered trademark of Oracle Corporation and/or its affiliates. Other names may be trademarks of their respective owners. Type 'help;' or '\h' for help. Type '\c' to clear the current input statement. mysql> inception get variables; ...
⑥ 接口:python接口
#!/usr/bin/python #-*- coding: utf-8 -*- import MySQLdb sql='/*--user=root;--password=123456;--host=127.0.0.1;--port=3306;--execute=1;*/\ inception_magic_start;\ use test;\ CREATE TABLE xxx(id int unsigned not null auto_increment comment "aaaa",username varchar(10) not null default 0 comment "xxx",primary key(id))engine = innodb default charset utf8mb4 comment "dddd";\ inception_magic_commit;' #insert into adaptive_office(username) values("ASD"),("ZXC"),("EST"); try: conn=MySQLdb.connect(host='127.0.0.1',user='root',passwd='',db='',port=6669) cursor=conn.cursor() cursor.execute(sql) results = cursor.fetchall() column_name_max_size=max(len(i[0]) for i in cursor.description) row_num=0 for result in results: row_num=row_num+1 print '*'.ljust(27,'*'),row_num,'.row', '*'.ljust(27,'*') row = map(lambda x, y: (x,y), (i[0] for i in cursor.description), result) for each_column in row: if each_column[0] != 'errormessage': print each_column[0].rjust(column_name_max_size),":",each_column[1] else: print each_column[0].rjust(column_name_max_size),':',each_column[1].replace('\n','\n'.ljust(column_name_max_size+4)) cursor.close() conn.close() except MySQLdb.Error,e: print "Mysql Error %d: %s" % (e.args[0], e.args[1])
效果:
python inc.py *************************** 1 .row *************************** ID : 1 stage : CHECKED errlevel : 0 stagestatus : Audit completed errormessage : None SQL : use test Affected_rows : 0 sequence : '0_0_0' backup_dbname : None execute_time : 0 sqlsha1 : *************************** 2 .row *************************** ID : 2 stage : CHECKED errlevel : 1 stagestatus : Audit completed errormessage : Set unsigned attribute on auto increment column in table 'xx'. SQL : CREATE TABLE xx(id int not null auto_increment comment "aaaa",username varchar(10) not null default 0 comment "xxx",primary key(id))engine = innodb default charset utf8mb4 comment "dddd" Affected_rows : 0 sequence : '0_0_1' backup_dbname : 127_0_0_1_3306_test execute_time : 0 sqlsha1 :
到此,Inception安裝已完成。更多的使用說明,可以從文檔說明里查找,文檔是最好的手冊指南。
2)安裝SQLAdvisor,架構和原理說明可以看美團點評SQL優化工具SQLAdvisor開源
① 下載
git clone https://github.com/Meituan-Dianping/SQLAdvisor.git
② 安裝依賴包
apt-get install cmake apt-get install libffi-dev apt-get install libaio-dev apt-get install glib2.0-dev apt-get install glib2.0 apt-get install percona-server-client-5.6 apt-get install percona-server-server-5.6 apt-get install percona-server-common-5.6 apt-get install libmysqlclient-dev apt-get install build-essential apt-get install g++ apt-get install bison
③ 相關修改
1:建立安裝目錄 mkdir -p /usr/local/sqlparser 2:增加軟連接 cd /usr/lib/x86_64-linux-gnu/ ls -lh /usr/lib/x86_64-linux-gnu/libperconaserverclient* ln -s libperconaserverclient_r.so.18 libperconaserverclient_r.so 3:修改配置 vi sqladvisor/CMakeLists.txt cmake_minimum_required (VERSION 2.6) project(sqladvisor) # /usr/local/sqlparser為sqlparser庫安裝目錄,必要時進行修改 include_directories("/usr/local/sqlparser/include") include_directories("/usr/local/sqlparser/include/regex") #include_directories("/usr/lib64/glib-2.0/include") include_directories("/usr/lib/x86_64-linux-gnu/glib-2.0/include") include_directories("/usr/include/glib-2.0") link_directories("/usr/local/sqlparser/lib") link_directories("/usr/lib/x86_64-linux-gnu") set(TEST_SRC main.cc) add_executable(sqladvisor ${TEST_SRC}) #如果是sqlparser debug庫,則應連接的庫為sqlparser-debug target_link_libraries(sqladvisor sqlparser-debug) target_link_libraries(sqladvisor perconaserverclient_r) target_link_libraries(sqladvisor glib-2.0)
④ 編譯依賴項sqlparser
1: cmake -DBUILD_CONFIG=mysql_release -DCMAKE_BUILD_TYPE=debug -DCMAKE_INSTALL_PREFIX=/usr/local/sqlparser ./ 2: make 3: make install
⑤ 安裝SQLAdvisor源碼
1: cd sqladvisor/ 2: cmake -DCMAKE_BUILD_TYPE=debug ./ 3: make
⑥ 測試:
sqladvisor --help Usage: sqladvisor [OPTION...] sqladvisor SQL Advisor Summary Help Options: -?, --help Show help options Application Options: -f, --defaults-file sqls file -u, --username username -p, --password password -P, --port port -h, --host host -d, --dbname database name -q, --sqls sqls -v, --verbose 1:output logs 0:output nothing

sqladvisor -h 127.0.0.1 -P 3306 -u root -p 123456 -d test -q "select * from xxx order by username " -v 1 2017-03-27 02:08:43 18111 [Note] 第1步: 對SQL解析優化之后得到的SQL:select `*` AS `*` from `test`.`xxx` order by `username` 2017-03-27 02:08:43 18111 [Note] 第2步:開始解析order by 條件 2017-03-27 02:08:43 18111 [Note] 第3步:開始驗證 字段username是不是主鍵。表名:xxx 2017-03-27 02:08:43 18111 [Note] show index from xxx where Key_name = 'PRIMARY' and Column_name ='username' and Seq_in_index = 1 2017-03-27 02:08:43 18111 [Note] 第4步:字段username不是主鍵。表名:xxx 2017-03-27 02:08:43 18111 [Note] 第5步:開始添加order by 字段 2017-03-27 02:08:43 18111 [Note] 第6步:開始驗證 字段username是不是主鍵。表名:xxx 2017-03-27 02:08:43 18111 [Note] show index from xxx where Key_name = 'PRIMARY' and Column_name ='username' and Seq_in_index = 1 2017-03-27 02:08:43 18111 [Note] 第7步:字段username不是主鍵。表名:xxx 2017-03-27 02:08:43 18111 [Note] 第8步:開始驗證 字段username是不是主鍵。表名:xxx 2017-03-27 02:08:43 18111 [Note] show index from xxx where Key_name = 'PRIMARY' and Column_name ='username' and Seq_in_index = 1 2017-03-27 02:08:43 18111 [Note] 第9步:字段username不是主鍵。表名:xxx 2017-03-27 02:08:43 18111 [Note] 第10步:開始驗證 字段username是不是主鍵。表名:xxx 2017-03-27 02:08:43 18111 [Note] show index from xxx where Key_name = 'PRIMARY' and Column_name ='username' and Seq_in_index = 1 2017-03-27 02:08:43 18111 [Note] 第11步:字段username不是主鍵。表名:xxx 2017-03-27 02:08:43 18111 [Note] 第12步:開始驗證表中是否已存在相關索引。表名:xxx, 字段名:username, 在索引中的位置:1 2017-03-27 02:08:43 18111 [Note] show index from xxx where Column_name ='username' and Seq_in_index =1 2017-03-27 02:08:43 18111 [Note] 第13步:開始輸出表xxx索引優化建議: 2017-03-27 02:08:43 18111 [Note] Create_Index_SQL:alter table xxx add index idx_username(username) 2017-03-27 02:08:43 18111 [Note] 第14步: SQLAdvisor結束!
到此,SQLAdvisor安裝已完成。更多的使用說明,可以從文檔說明里查找,文檔是最好的手冊指南。
1)和2)即Inception和SQLAdvisor已經解決了大部分場景的審核要求,通過他們各自的說明手冊了解其使用方法就可以直接通過web來操作實現了。
3)Tornado實現web
① 安裝
1: apt-get install python-setuptools 2: easy_install tornado 3: apt-get install python-mysqldb
4:
easy_install futures
② 初始化MySQL(上面已經裝好了mysql server)

CREATE DATABASE `sql_audit` USE `sql_audit`; #SQLAdvisor使用 DROP TABLE IF EXISTS `slave_dbnames`; CREATE TABLE `slave_dbnames` ( `id` int(10) unsigned NOT NULL AUTO_INCREMENT, `dbname` varchar(30) NOT NULL, `createTime` datetime NOT NULL, PRIMARY KEY (`id`), UNIQUE KEY `uniq_dbname` (`dbname`) ) ENGINE=InnoDB AUTO_INCREMENT=136 DEFAULT CHARSET=utf8; #下面2張Inception使用 DROP TABLE IF EXISTS `sysuser`; CREATE TABLE `sysuser` ( `id` int(11) unsigned NOT NULL AUTO_INCREMENT COMMENT '主鍵', `username` varchar(30) NOT NULL COMMENT '用戶名', `password` varchar(100) NOT NULL COMMENT '密碼', `email` varchar(100) NOT NULL COMMENT '郵箱', `createTime` datetime NOT NULL, PRIMARY KEY (`id`), UNIQUE KEY `uk_username` (`username`), UNIQUE KEY `uk_email` (`email`) ) ENGINE=InnoDB AUTO_INCREMENT=55 DEFAULT CHARSET=utf8 COMMENT='用戶信息表'; DROP TABLE IF EXISTS `user_dbnames`; CREATE TABLE `user_dbnames` ( `id` int(10) unsigned NOT NULL AUTO_INCREMENT COMMENT '主鍵', `username` varchar(30) NOT NULL COMMENT '用戶名', `dbname` varchar(30) NOT NULL COMMENT '數據庫名', `createTime` datetime NOT NULL COMMENT '創建時間', PRIMARY KEY (`id`), UNIQUE KEY `uk_username_dbname` (`username`,`dbname`) ) ENGINE=InnoDB AUTO_INCREMENT=368 DEFAULT CHARSET=utf8 COMMENT='用戶操作數據庫對應表';
③ 測試效果
web部分的代碼就不說明了,主要就是傳參數使用Inception和SQLAdvisor。我使用的模板來自:http://ace.jeka.by/index.html。
運行:
python audit_server.py Inception --port=6669
最終實現的效果如下:
4)Supervisor來實現后台進程啟動
具體的可以看進程管理supervisor的簡單說明,這里需要注意的是上面的安裝都是通過root的,而Inception和SQLAdivsor以及Tornado的使用都不需要用root進行啟動,為了安全,安裝完所有之后,專門創建啟動上面進程都用戶,如:
ps -ef| grep incept #inception用戶啟動inception incepti+ 3021 3015 0 Mar14 ? 00:00:00 /usr/bin/Inception --defaults-file=/etc/inception/inc.cnf ps -ef| grep tornado | grep -v "color=auto" #tornado用戶啟動tornado tornado 26529 3015 0 Mar22 ? 00:00:06 /usr/bin/python /home/jyzhou/audit_platform/audit_server.py SQLAdvisor 是一個執行文件,直接使用就可以了。
總結:
通過上面大致就完成了一個web審核管理平台,本文主要是介紹ubuntu下如何安裝Inception和SQLAdvisor,Centos可以直接看它們的手冊說明。
參考文檔: