比較兩個mysql資料庫裡面的表是否相同的一個校驗指令碼

czxin788發表於2015-12-05
比較兩個mysql資料庫裡面的表是否相同的一個校驗指令碼


一、原理:採用CRC32演算法進行校驗。那麼什麼是CRC32演算法呢?CRC32演算法 的計算是非常非常非常嚴格的。嚴格到什麼程度呢?你的程式只要被改動了一個位元組(甚至只是大小寫的改動),它的值就會跟原來的不同。所以只要給你的“原”程式計算好CRC值,儲存在某個地方,然後在程式中隨機地再對檔案進行CRC校驗,接著跟第一次生成並儲存好的CRC值進行比較,如果相等的話就說明你的程式沒有被修改/破解過,如果不等的話,那麼很可能你的程式遭到了病毒的感染,或者被Cracker用16進位制工具暴力破解過了。


二、指令碼內容
[root@drbd-01 ~]#cat checksum.sh
#!/bin/bash
split=`echo + -{1..86} +| tr -d "[0-9]|"`
echo $split > /home/mysql/checksum/$5.checksum
printf  "| %-40s   | %-40s| \n" TABLE_NAME CHECKSUM >> /home/mysql/checksum/$5.checksum
echo $split >> /home/mysql/checksum/$5.checksum
for table_name in `mysql -u$1 -p$2 -h$3 -P$4 -BNe "select table_name from information_schema.tables where table_schema='$5' and table_type='base table';"`
do
        column_name=`mysql -u$1 -p$2 -h$3 -P$4 -BNe "select column_name from information_schema.columns where table_schema='$5' and table_name='$table_name';"|tr '\n' ','|sed 's/,/\`,\`/g'|sed 's/^/\`/'|sed 's/,\`$//'`
 
        if_one_column=`echo $column_name|grep ,`
        if [ -z $if_one_column ];then
                checksum=`mysql  -u$1 -p$2 -h$3 -P$4 -BNe "select sql_no_cache COALESCE(LOWER(CONV(BIT_XOR(CAST(CRC32($column_name) AS UNSIGNED)), 10, 16)), 0) as checksum from $5.$table_name;"`
        else
                checksum=`mysql -u$1 -p$2 -h$3 -P$4 -BNe "select sql_no_cache COALESCE(LOWER(CONV(BIT_XOR(CAST(CRC32(CONCAT_WS('',$column_name)) AS UNSIGNED)), 10, 16)), 0) as checksum from $5.$table_name;"`
        fi
        printf  "| %-40s   | %-40s| \n" $table_name $checksum >> /home/mysql/checksum/$5.checksum
 
done
 
echo $split >> /home/mysql/checksum/$5.checksum


三、執行指令碼的方法
sh checksum.sh user passwd localhost 3306 dbname


四、例子
4.1、建立一個如下目錄,用來存放校驗碼:
[root@drbd-01 ~]#mkdir /home/mysql/checksum/
4.2、如下方法執行指令碼,用來對db1庫裡面的表進行校驗:
[root@drbd-01 ~]# sh checksum.sh root "123" localhost 3306  db1
4.3、到 /home/mysql/checksum/目錄下檢視生成的校驗值:
[root@drbd-01 ~]# cat /home/mysql/checksum/db1.checksum 
+ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - +
| TABLE_NAME                                 | CHECKSUM                                | 
+ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - +
| t1                                         | 77073096                                | 




4.4、重複上述4.2步驟,對其他機器上的資料庫也生成校驗碼;
4.5、對比兩個機器生成的校驗碼,如果值不同,表明對比的兩張表資料不一樣。


完。

來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/28916011/viewspace-1854138/,如需轉載,請註明出處,否則將追究法律責任。

相關文章