python制作mysql数据迁移脚本


Posted in Python onJanuary 01, 2019

用python写了个数据迁移脚本,主要是利用从库将大的静态表导出表空间,载导入到目标实例中。

#!/usr/bin/env python3
#-*- coding:utf8 -*-
#author:zhanbin.liu
#!!!!!DB必须同版本
#python3环境  pip3 install pymysql paramiko

import os
#from pathlib import Path
import sys
import pymysql
import paramiko

#每次只能迁移一个DB下的表,到指定DB
#GRANT SELECT, CREATE, RELOAD, ALTER, LOCK TABLES ON *.* TO 'data_migration'@'192.168.%' IDENTIFIED BY 'data_migration@123';
tables='sqlauto_cluster,sqlauto_user'    #以,分割的字符串,如a,b,c
tableList = tables.split(',')
sourceIp = '192.168.1.101'
sourceDataBase = '/data/mysql/3306/data'
sourceDbName = 'inception_web'
sourceDataDir = os.path.join(sourceDataBase,sourceDbName)
desIp = '192.168.1.102'
desDataBase = '/data/mysql/3306/data'
desDbName = 'inception_web'
desDataDir = os.path.join(desDataBase,desDbName)

# for table in tableList:
#   desFile = Path("%s/%s.ibd" %(desDataDir,table))
#   print(desFile)
#   if desFile.is_file():
#     print("ok")
#   else:
#     print("no")

comUser = 'data_migration'
comPwd = 'data_migration@123'
comPort = 3306

client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())

def table_judge():
  print("table_judge")
  sourceTableExist = pymysql.connect(sourceIp,comUser,comPwd,sourceDbName,comPort,charset='utf8')
  desTableExist = pymysql.connect(desIp,comUser,comPwd,desDbName,comPort,charset='utf8')
  sourceTables = []
  desTables = []
  cursor_source = sourceTableExist.cursor()
  cursor_des = desTableExist.cursor()

  for table in tableList:
    #print(table)
    cursor_source.execute("select TABLE_NAME from information_schema.TABLES where TABLE_SCHEMA='%s' and TABLE_NAME='%s';" % (sourceDbName,table))
    sourceTable_tmp = cursor_source.fetchall()
    cursor_des.execute("select TABLE_NAME from information_schema.TABLES where TABLE_SCHEMA='%s' and TABLE_NAME='%s';" % (desDbName,table))
    desTable_tmp = cursor_des.fetchall()
    #print(desTable_tmp)
    if sourceTable_tmp is ():
      sourceTables.append(table)
    if desTable_tmp is not ():
      desTables.append(desTable_tmp[0][0])
  sourceTableExist.close()
  desTableExist.close()

  s=d=0
  if sourceTables != []:
    print('迁移源不存在将要迁移的表:',sourceIp,sourceDbName, sourceTables,' 请检查')
    s=1
  if desTables != []:
    print('目标库存在将要迁移的表:',desIp,desDbName,desTables,' 请移除')
    d=1
  if s == 1 or d == 1:
    sys.exit()

def data_sync():
  print('data_sync')
  db_source = pymysql.connect(sourceIp,comUser,comPwd,sourceDbName,comPort,charset='utf8')
  db_des = pymysql.connect(desIp,comUser,comPwd,desDbName,comPort,charset='utf8')
  cursor_db_source = db_source.cursor()
  cursor_db_des = db_des.cursor()

  for table in tableList:
    print("正在同步表:",table)
    cursor_db_source.execute("show create table %s;" % (table))
    createTableSQL = cursor_db_source.fetchall()[0][1]
    print(createTableSQL)
    try:
      cursor_db_des.execute(createTableSQL)
    except Exception as error:
      print(error)
    cursor_db_source.execute("flush table %s with read lock;" % (table))
    cursor_db_des.execute("alter table %s discard tablespace;" % (table))

    client.connect(sourceIp, 22, 'root')
    stdin1, stdout1, stderr1 = client.exec_command("scp %s %s:%s " % (sourceDataDir+"/"+table+".ibd", desIp, desDataDir))
    stdin2, stdout2, stderr2 = client.exec_command("scp %s %s:%s " % (sourceDataDir+"/"+table+".cfg", desIp, desDataDir))
    a_e_1 = stderr1.readlines()
    a_e_2 = stderr2.readlines()
    if a_e_1 != [] or a_e_2 != []:
      print(a_e_1,a_e_2)
      sys.exit()
    client.close()

    client.connect(desIp, 22, 'root')
    stdin3, stdout3, stderr3 = client.exec_command("chown -R mysql.mysql %s*" % (desDataDir+"/"+table))
    a_e_3 = stderr3.readlines()
    if a_e_3 != []:
      print(a_e_1, a_e_2)
      sys.exit()
    client.close()
    #cursor_db_source.execute("select sleep(10);")
    cursor_db_source.execute("unlock tables;")
    cursor_db_des.execute("alter table %s import tablespace;" % (table))
    print("同步完成")

  cursor_db_source.close()
  cursor_db_des.close()

def data_checksum():
  print('data_checksum')
  db_source = pymysql.connect(sourceIp,comUser,comPwd,sourceDbName,comPort,charset='utf8')
  db_des = pymysql.connect(desIp,comUser,comPwd,desDbName,comPort,charset='utf8')
  cursor_db_source = db_source.cursor()
  cursor_db_des = db_des.cursor()

  for table in tableList:
    print("正在校验表:", table)
    cursor_db_source.execute("checksum table %s;" % (table))
    ck_s = cursor_db_source.fetchall()[0][1]
    cursor_db_des.execute("checksum table %s;" % (table))
    ck_d = cursor_db_des.fetchall()[0][1]
    if ck_s != ck_d:
      print("表不一致:",table)
    else:
      print("表一致:",table)

  cursor_db_source.close()
  cursor_db_des.close()

if __name__ == "__main__":
  table_judge()
  data_sync()
  data_checksum()
  print('haha')
Python 相关文章推荐
python实现根据主机名字获得所有ip地址的方法
Jun 28 Python
python bottle框架支持jquery ajax的RESTful风格的PUT和DELETE方法
May 24 Python
Python微信库:itchat的用法详解
Aug 14 Python
解决pycharm的Python console不能调试当前程序的问题
Jan 20 Python
python使用wxpy实现微信消息防撤回脚本
Apr 29 Python
centos 安装Python3 及对应的pip教程详解
Jun 28 Python
python变量的存储原理详解
Jul 10 Python
Python之time模块的时间戳,时间字符串格式化与转换方法(13位时间戳)
Aug 12 Python
Python (Win)readline和tab补全的安装方法
Aug 27 Python
Django实现将views.py中的数据传递到前端html页面,并展示
Mar 16 Python
django haystack实现全文检索的示例代码
Jun 24 Python
关于Python错误重试方法总结
Jan 03 Python
在python中将字符串转为json对象并取值的方法
Dec 31 #Python
对python中Json与object转化的方法详解
Dec 31 #Python
python使用zip将list转为json的方法
Dec 31 #Python
python 获取utc时间转化为本地时间的方法
Dec 31 #Python
python 实现UTC时间加减的方法
Dec 31 #Python
Python从单元素字典中获取key和value的实例
Dec 31 #Python
对Python 两大环境管理神器 pyenv 和 virtualenv详解
Dec 31 #Python
You might like
ezSQL PHP数据库操作类库
2010/05/16 PHP
php文件缓存方法总结
2016/03/16 PHP
PHP判断JSON对象是否存在的方法(推荐)
2016/07/06 PHP
jQuery 剧场版 你必须知道的javascript
2009/05/27 Javascript
Jquery下attr和removeAttr的使用方法
2010/12/28 Javascript
jQuery学习笔记 获取jQuery对象
2012/09/19 Javascript
Jquery UI震动效果实现原理及步骤
2013/02/04 Javascript
多种方法判断Javascript对象是否存在
2013/09/22 Javascript
Javascript调用函数方法的几种方式介绍
2015/03/20 Javascript
最精简的JavaScript实现鼠标拖动效果的方法
2015/05/11 Javascript
javascript实现判断鼠标的状态
2015/07/10 Javascript
javascript基础知识分享之类与函数化
2016/02/13 Javascript
BootStrap实现邮件列表的分页和模态框添加邮件的功能
2016/10/13 Javascript
Ztree新增角色和编辑角色回显问题的解决
2016/10/25 Javascript
从零开始学习Node.js系列教程之基于connect和express框架的多页面实现数学运算示例
2017/04/13 Javascript
ReactNative短信验证码倒计时控件的实现代码
2017/07/20 Javascript
微信小程序授权登录及解密unionId出错的方法
2018/09/26 Javascript
JavaScript函数式编程(Functional Programming)高阶函数(Higher order functions)用法分析
2019/05/22 Javascript
bootstrap datepicker的基本使用教程
2019/07/09 Javascript
解决vuex刷新状态初始化的方法实现
2019/08/15 Javascript
JavaScript动画实例之粒子文本的实现方法详解
2020/07/28 Javascript
微信小程序实现点击生成随机验证码
2020/09/09 Javascript
详解ES6 扩展运算符的使用与注意事项
2020/11/12 Javascript
[01:26]DOTA2荣耀之路2:iG,China
2018/05/24 DOTA
Python 迭代,for...in遍历,迭代原理与应用示例
2019/10/12 Python
使用OpenCV实现人脸图像卡通化的示例代码
2021/01/15 Python
德国综合购物网站:OTTO
2018/11/13 全球购物
学期研究性学习个人的自我评价
2014/01/09 职场文书
2014年商场超市庆元旦活动方案
2014/02/14 职场文书
事务机电主管工作职责
2014/02/25 职场文书
销售经理竞聘书
2014/03/31 职场文书
学校教师安全责任书
2014/07/23 职场文书
危货运输企业安全生产责任书
2014/07/28 职场文书
如何写辞职书
2015/02/26 职场文书
教你用python实现一个无界面的小型图书管理系统
2021/05/21 Python
教你使用Python pypinyin库实现汉字转拼音
2021/05/27 Python