提取MySQL binlog中指定表的操作記錄

舊夢依稀發表於2017-05-15
一段簡單的Python指令碼,需要本地裝了合適版本的mysqlbinlog工具。
支援Python 2.7+



點選(此處)摺疊或開啟

  1. #_*_ coding:utf-8 _*_

  2. import sys
  3. import os
  4. import io

  5. binlogfile = sys.argv[1]
  6. database_name = sys.argv[2]
  7. table_name = sys.argv[3]

  8. def format_binlog():
  9.     os.system('mysqlbinlog --base64-output=decode-rows -v '+binlogfile+'>'+binlogfile+'.txt')

  10. def pickupbinlog():
  11.     f = io.open(binlogfile+'.txt','r')
  12.     fw = io.open(database_name+'_'+table_name+'.txt','a')
  13.     priv_str = ''
  14.     priv_line = ''
  15.     goal_flag = 0
  16.     for row in f:
  17.         # 處理首行
  18.         if row[0:3] == '###' and priv_str != '###':
  19.             if database_name in row and table_name in row:
  20.                 goal_flag = 1
  21.                 fw.write(priv_line)
  22.                 fw.write(row)
  23.         # 處理末行
  24.         if row[0:3] != '###' and priv_str == '###':
  25.             goal_flag = 0
  26.         # 處理目標操作
  27.         if row[0:3] == '###' and priv_str == '###' and goal_flag == 1:
  28.             fw.write(row)
  29.         priv_str = row[0:3]
  30.         priv_line = row
  31.     f.close()
  32.     fw.close()

  33. if __name__ == '__main__':
  34.     # python2.7 pickupbinlog.py mysql-bin.001051 dbname tablename
  35.     # python3 pickupbinlog.py mysql-bin.001051 dbname tablename
  36.     format_binlog()
  37.     pickupbinlog()


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

相關文章