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

#!/usr/bin/envpython

#-*- coding: utf-8 -*-import MySQLdb

importtimeimport 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 indb_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=0self.execSQLlock(cur)

flush_m="flush logs"cur.execute(flush_m)whileTrue:

data=[]

slave_pos=[]

n=n+1exe_sql="select Command,State,Info,Id from information_schema.processlist"cur.execute(exe_sql)

plist=cur.fetchall()for li inrange(len(plist)):if plist[li][0]=="Query" and plist[li][1]=="Waiting for global read lock":

lock_id="kill" + str(plist[li][3])

print plist[li][2]

cur.execute(lock_id)

slave_pos.append(self.execIo(cur1,"show master status")[1])

data.append(self.execIo(cur1,"show slave status")[6]) ##从库的游标time.sleep(1)

slave_pos.append(self.execIo(cur1,"show master status")[1])

data.append(self.execIo(cur,"show master status")[1])##从库的游标

print".......",data,slave_posif data[0]==data[1] and slave_pos[0]==slave_pos[1]:

try:

print"第%s次判断数据已经同步....."%nif 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[1])+"‘"+",master_user=‘"+args[2]+"‘"+",master_password=‘"+args[3]+"‘,master_port="+str(args[4])+",MASTER_LOG_FILE=‘"+str(new_pos[0][0])+"‘"+",MASTER_LOG_POS="+str(new_pos[0][1])

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(5)

s_pos=self.exeStop(cur,"show slave status;")

#print s_pos[0][10],s_pos[0][11]if s_pos[0][10]=="Yes" and s_pos[0][11]=="Yes":

self.exeStop(cur1,"reset slave all")

print"主从切换成功!"print"\n"

whileTrue:

print

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值