MySQL数据库主从切换脚本自动化

本文转载自:https://blog.csdn.net/weixin_36135773/article/details/79514507

在一些实际环境中,如何实现主从的快速切换,在没有MHA等工具的辅助下,如何避免影响线上的业务,一般都会在在业务低峰期进行主从切换,本脚本主要利用MySQL自带的命令行工具(FLUSH TABLES WITH READ LOCK)进行锁全库,且由用户自行输入判断多少秒内从库BINLOG数据不在同步后,认为主从数据已达一致性可以进行主从切换(在一些资料上说也可以用READ-ONLY来锁库,但需要注意如果写入用户具有Admin权限是不受限制),主从切换完成5秒后进行检查主从是否同步问题.

连接数据库使用TCP/IP方式,需要相应的操作数据库权限。

目前判断使用show master status 来判断,可以show slave status返回的值来判断,自行修改。

yum install MySQL-python

脚本:switch_master_slave.py

#!/usr/bin/env python
# -*- coding: utf- -*-
import MySQLdb
import time
import sys
class m_s:
def __init__(self,host,user,password,port):
self.host=host
self.user=user
self.passowrd=password
self.port=port
def getConn(self,db="mysql"):
try:
conn=MySQLdb.connect(host=self.host, user=self.user, passwd=self.passowrd, db=db, port=self.port, charset="utf8")
cur = conn.cursor()
return cur
except Exception as e:
return e
def execSQLlock(self,*args):
flush_sql="FLUSH TABLES WITH READ LOCK"
cur.execute(flush_sql)
def execIo(self,cur,command):
cur.execute(command)
db_pos = cur.fetchall()
for value in db_pos:
value=value
return value
def exeStop(self,cur,command):
cur.execute(command)
db_pos = cur.fetchall()
return db_pos
def execSQLstatus(self,*args):
n=
self.execSQLlock(cur)
flush_m = "flush logs"
cur.execute(flush_m)
while True:
data=[]
slave_pos=[]
n=n+
exe_sql = "select Command,State,Info,Id from information_schema.processlist"
cur.execute(exe_sql)
plist = cur.fetchall()
for li in range(len(plist)):
if plist[li][] == "Query" and plist[li][] == "Waiting for global read lock":
lock_id = "kill " + str(plist[li][])
print plist[li][]
cur.execute(lock_id)
slave_pos.append(self.execIo(cur1, "show master status")[])
data.append(self.execIo(cur1,"show slave status")[]) ##从库的游标
time.sleep()
slave_pos.append(self.execIo(cur1, "show master status")[])
data.append(self.execIo(cur,"show master status")[])##从库的游标
print ".......",data,slave_pos
if data[]==data[] and slave_pos[]==slave_pos[]:
try:
print "第%s次判断数据已经同步....."%n
if n==c_time:
print "开始主从切换工作........"
self.exeStop(cur1,"stop slave") ##停止从库同步
new_pos=self.exeStop(cur1,"show master status")#获取新主库的FILE和POS的值,游标为还没切换前的从库
#print "获取新主库的FILE和POS的值,游标为还没切换前的从库",new_pos
self.exeStop(cur,"reset master;")##主库释放从库主从信息......
##在从库执行new_change 指向新的主库
self.exeStop(cur1,"reset slave all")
new_change="change master to master_host='"+str(args[])+"'"+",master_user='"+args[]+"'"+",master_password='"+args[]+"',master_port="+str(args[])+",MASTER_LOG_FILE='"+str(new_pos[][])+"'"+",MASTER_LOG_POS="+str(new_pos[][])
print new_change
self.exeStop(cur,new_change)##在原来主库上执行change master to.....
#print "在原来主库上执行change master to...."
self.exeStop(cur,"start slave") ##在原来主库上执行change master to.....
time.sleep()
s_pos=self.exeStop(cur,"show slave status;")
#print s_pos[][],s_pos[][]
if s_pos[][]=="Yes" and s_pos[][]=="Yes":
self.exeStop(cur1,"reset slave all")
print "主从切换成功!"
print "\n"
while True:
print "等待其他操作完成,即将unlock tables主库......"
try:
stop = raw_input("输入终止命令q即完成此次操作:\n")
if stop == "q":
sys.exit()
# break
except Exception as e:
print "good bye" else:
print s_pos[][]
break
except Exception as e:
return e
else:
print "主从数据未达到一致性..........",n
n=
data=[] if __name__ =="__main__":
c_time=int(raw_input("多少秒后进行主从切换..>>"))
print "****************************************************\n" print "请根据提示输入指定信息:"
m_host = raw_input("目前主库的地址:")
m_user = raw_input("目前主库的登陆用户名:")
m_password = raw_input("目前主库的密码:")
m_port = int(raw_input("目前主库的端口:"))
print "****************************************************\n"
s_host = raw_input("目前从库的地址:")
s_user = raw_input("目前从库的登陆用户名:")
s_password = raw_input("目前从库的密码:")
s_port = int(raw_input("目前从库的端口:"))
M = m_s(m_host, m_user, m_password, m_port)
S = m_s(s_host,s_user,s_password,s_port)
cur = M.getConn() ##获取主库游标
cur1 = S.getConn() ##获取从库游标
print "*****************************************************\n"
print "主从同步用户信息.........\n"
s_user1 = raw_input("输入主从同步的用户>>:")
s_password1 = raw_input("输入主从同步的密码:")
s_port1 = int(raw_input("输入主从同步的端口:")) M.execSQLstatus(cur,s_host,s_user1,s_password1,s_port1)
# python switch_master_slave.py
多少秒后进行主从切换..>>
**************************************************** 请根据提示输入指定信息:
目前主库的地址:192.168.56.100
目前主库的登陆用户名:wanbin
目前主库的密码:mysql
目前主库的端口:
**************************************************** 目前从库的地址:192.168.56.200
目前从库的登陆用户名:wanbin
目前从库的密码:mysql
目前从库的端口:
***************************************************** 主从同步用户信息......... 输入主从同步的用户>>:repl
输入主从同步的密码:wanbin
输入主从同步的端口:
....... [234L, 234L] [250L, 250L]
第1次判断数据已经同步.....
....... [234L, 234L] [250L, 250L]
第2次判断数据已经同步.....
....... [234L, 234L] [250L, 250L]
第3次判断数据已经同步.....
....... [234L, 234L] [250L, 250L]
第4次判断数据已经同步.....
....... [234L, 234L] [250L, 250L]
第5次判断数据已经同步.....
开始主从切换工作........
change master to master_host='192.168.56.200',master_user='repl',master_password='wanbin',master_port=,MASTER_LOG_FILE='my3306_binlog.000018',MASTER_LOG_POS=
switch_master_slave.py:: Warning: Sending passwords in plain text without SSL/TLS is extremely insecure.
cur.execute(command)
switch_master_slave.py:: Warning: Storing MySQL user name or password information in the master info repository is not secure and is therefore not recommended. Please consider using the USER and PASSWORD connection options for START SLAVE; see the 'START SLAVE Syntax' in the MySQL Manual for more information.
cur.execute(command)
主从切换成功! 等待其他操作完成,即将unlock tables主库......
输入终止命令q即完成此次操作: 等待其他操作完成,即将unlock tables主库......
输入终止命令q即完成此次操作:
q
等待其他操作完成,即将unlock tables主库......
输入终止命令q即完成此次操作:
q

MySQL数据库主从切换脚本自动化的更多相关文章

  1. Spring AOP实现Mysql数据库主从切换(一主多从)

    设置数据库主从切换的原因:数据库中经常发生的是“读多写少”,这样读操作对数据库压力比较大,通过采用数据库集群方案, 一个数据库是主库,负责写:其他为从库,负责读,从而实现读写分离增大数据库的容错率.  ...

  2. mysql+keepalived主从切换脚本 转

    Keepalived MySQL故障自动切换脚本   MySQL架构为master-slave(主从),master故障自动切换到slave上.当然也可以设置为双master,但这里有个弊端:就是当主 ...

  3. (转)Mysql数据库主从心得整理

    Mysql数据库主从心得整理 原文:http://blog.sae.sina.com.cn/archives/4666 管理mysql主从有2年多了,管理过200多组mysql主从,几乎涉及到各个版本 ...

  4. Linux下定时备份MySQL数据库的Shell脚本

    Linux下定时备份MySQL数据库的Shell脚本   对任何一个已经上线的网站站点来说,数据备份都是必须的.无论版本更新还是服务器迁移,备份数据的重要性不言而喻.人工备份数据的方式不单耗费大量时间 ...

  5. MySQL数据库主从同步实战过程

       Linux系统MySQL数据库主从同步实战过程 安装环境说明 系统环境: [root@~]# cat /etc/redhat-release CentOS release 6.5 (Final) ...

  6. mysql数据库主从同步

    环境: Mater:   CentOS7.1  5.5.52-MariaDB  192.168.108.133 Slave:   CentOS7.1  5.5.52-MariaDB  192.168. ...

  7. mysql数据库主从同步读写分离(一)主从同步

    1.mysql数据库主从同步读写分离 1.1.主要解决的生产问题 1.2.原理 a.为什么需要读写分离? 一台服务器满足不了访问需要.数据的访问基本都是2-8原则. b.怎么做?  不往从服务器去写了 ...

  8. MySQL数据库主从同步延迟分析及解决方案

    一.MySQL的数据库主从复制原理 MySQL主从复制实际上基于二进制日志,原理可以用一张图来表示: 分为四步走: 1. 主库对所有DDL和DML产生的日志写进binlog: 2. 主库生成一个 lo ...

  9. mysql数据库分库备份脚本

    mysql数据库分库备份脚本 版本1 for dbname in `mysql -uroot -poldboy123 -e "show databases;" |grep -Evi ...

随机推荐

  1. Python web前端 10 bootstrp

    Python web前端 10 bootstrp 1.媒体查询 <style> *{ margin: 0; padding: 0; } div{ width: 110px; height: ...

  2. NET Core 2.1.0 now available

    ASP.NET Core 2.1.0 now available https://blogs.msdn.microsoft.com/webdev/2018/05/30/asp-net-core-2-1 ...

  3. linux批量替换指定文件夹中所有文件的指定内容

    命令:sed -i "s#https#http#g" `grep http -rl VEROMODA` 功能:用来替换当前目录VEROMODA文件夹及子文件夹中所有文件中的http ...

  4. Even-odd Boxes hackerrank 分类讨论

    https://www.hackerrank.com/contests/101hack50/challenges/even-and-odd-boxes/editorial 昨晚做的时候卡了挺久的. 首 ...

  5. 牛客网Java刷题知识点之关键字static、static成员变量、static成员方法、static代码块和static内部类

    不多说,直接上干货! 牛客网Java刷题知识点之关键字static static代表着什么 在Java中并不存在全局变量的概念,但是我们可以通过static来实现一个“伪全局”的概念,在Java中st ...

  6. 在东京生活的中国IT程序员

    应之前文章的博友邀请,我来开一篇在日本东京生活的中国IT程序员自谈,文中的讨论对象多为我自己或者是我的中国人(前)同事,有以偏概全之处还请包涵. 首先,我之前说日本的IT并不发达,不发达到什么程度呢? ...

  7. Linux大棚版vimrc配置

    Linux大棚版vimrc配置—V2.0版本,如下: [shell] $cat .vimrc “== “Author :roc “Website:roclinux.cn “Version:2.0 “= ...

  8. untiy3d开发环境搭建和开发准备

    1.到untiy3d官网上下载untiy3d的软件(这里我使用的是个人版的5.3.61f做学习使用) 2.安装vs2012 3.因为unity3d和vs的版本有一定的版本对应关系,我这里使用vs201 ...

  9. Lodop套打

    记录一下Lodop套打模板 实现打印功能需电脑已经连接打印机(打印什么类型的东西就连接相应的打印机 (普通大打印机 打印标签 打印发票各种打印机))和已经安装好lodop控件 控件可到官网进行下载 h ...

  10. 用TextWriterTraceListener实现建议log文件记录

    log4net之类3方组件确实很方便,但是想写个小小的demo之类的程序,有点用不起啊. 微软自带的TraceListener要实现一个简易的日志帮助类还是很简单的,直接上代码,自己备用,也希望对同样 ...