Python自动创建MySQL的从库脚本
本脚本主要用于创建mysql主从的从库,并且主库已经配置好相关的主从参数,主库上面有需要同步的数据库备份,在从库上执行此脚本,通过内网取得主库的配置文件、数据库备份、主库的权限库等用于从库的创建,自动获得需要同步主库的bin-log位置及pos点(本脚本的备份是晚上0点备份,此脚本已经在我公司多个游戏数据库上应用,还不错,大家可以看看!
- #!/usr/bin/env Python
- # -*- coding: utf-8 -*-
- ##############################################################################
- # @Author: wangwei
- # @E-mail: [email protected]
- # @Create Date: 2012-06-19
- # @Version: V1
- #注意事项:1、主库已经按照要求修改配置文件打开了bin-log,设置了相关参数
- # 2、从库已经安装和主库一样版本的mysql
- # 3、运行之后删除/data1/目录下的压缩包
- # 4、运行格式:python create_slave.py 根据提示输入主库的内网地址
- # 5、在执行check_mysql时,会出现Broken pipe的错误,这个是由于python调用系统命令关闭和打开mysql时显示的信息没有正确的显示在终端造成的,没有影响,暂时没有找到不让显示此类信息的方法,亟待解决
- ##############################################################################
- import paramiko,os,sys,datetime,time,MySQLdb
- class Database:
- def __init__(self,host):
- self.user='root'
- self.password='14314'
- self.port=10000
- self.today=datetime.date.today().strftime('%Y%m%d')
- self.bindir='/data1/mysql_log'
- self.host=host
- if not os.path.isdir(self.bindir):
- os.mkdir(self.bindir)
- os.popen("ln -s /data1/mysql_log /mysql_log")
- if not os.path.isdir('/data1/mysql_log/binlog'):
- os.mkdir('/data1/mysql_log/binlog')
- if not os.path.isdir('/data1/mysql_log/relaylog'):
- os.mkdir('/data1/mysql_log/relaylog')
- os.popen("chown -R mysql.mysql /data1/mysql_log/")
- def check_mysql(self):#检查从库nysql数据库服务是否运行,如在运行则pkill掉,然后跳过权限表启动,为导入数据做准备
- print "\033[1;32;40m%s\033[0m" % "Check mysql now,Please wait...."
- if not os.path.isdir("/usr/local/mysql"):
- print "\033[1;31;40m%s\033[0m" % " Mysql not install,Please install mysql !"
- sys.exit()
- if os.popen("netstat -ntlp|grep 3306|wc -l").read().strip() != '0':
- os.popen("pkill mysqld")
- time.sleep(5)
- conm = "/usr/local/mysql/bin/mysqld_safe --defaults-file=/usr/local/mysql/etc/innodb.cnf --datadir=/home/mysql/data --user=mysql --skip-grant-tables &"
- os.popen(conm)
- time.sleep(5)
- if os.popen("netstat -ntlp|grep 3306|wc -l").read().strip() == '0':
- print "\033[1;31;40m%s\033[0m" % "Mysql not Running,please start with '--skip-grant-tables' !"
- sys.exit()
- def export_table(self):#导出当前主库的表结构和备份mysql权限库
- print "\033[1;32;40m%s\033[0m" % "Export master table and back mysql,Please wait ...."
- try:
- s=paramiko.SSHClient()
- s.set_missing_host_key_policy(paramiko.AutoAddPolicy())
- s.connect(self.host,self.port,self.user,self.password)
- conm = "/usr/local/mysql/bin/mysqldump --add-drop-table -udump -p1443214234 -d -B test adb ddb tdb|bzip2 -2 > /data/script/db_back/table_%s.bz2 && tar -zcvf /data/script/db_back/mysql.tgz /home/mysql/data/mysql && cp -f /usr/local/mysql/etc/innodb.cnf /data/script/db_back/ && echo $?" % self.today
- stdin,stdout,stderr=s.exec_command(conm)
- result = stdout.readlines()[-1].strip()
- s.close()
- if result == '0':
- print " Export_table success !"
- else:
- print "\033[1;31;40m%s\033[0m" % "Export_table Error !"
- sys.exit()
- except Exception,e:
- print "\033[1;31;40m%s\033[0m" % "SSH connect Error !"
- sys.exit()
- def down_back(self):#拷贝主库当天的数据库备份和表结构
- local_dir='/data1/'
- remote_dir='/data/script/db_back/'
- try:
- t=paramiko.Transport((self.host,self.port))
- t.connect(username=self.user,password=self.password)
- sftp=paramiko.SFTPClient.from_transport(t)
- files=sftp.listdir(remote_dir)
- print "\033[1;32;40m%s\033[0m" % "Download back file,Please wait ...."
- print ' Beginning to download file from %s %s ' % (self.host,datetime.datetime.now())
- for f in files:
- if f.find(self.today) != -1 or f == 'mysql.tgz' or f == 'innodb.cnf':
- print ' Downloading file:',self.host + ':' + os.path.join(remote_dir,f)
- sftp.get(os.path.join(remote_dir,f),os.path.join(local_dir,f))
- #sftp.put(os.path.join(local_dir,f),os.path.join(remote_dir,f))
- t.close()
- print ' Download All back file success %s ' % datetime.datetime.now()
- except Exception,e:
- print "\033[1;31;40m%s\033[0m" % "SFTP connect Error !"
- sys.exit()
- def unbz2(self):#解压拷贝的数据库备份和表结构bz2包
- print "\033[1;32;40m%s\033[0m" % "Decompression file,Please wait ...."
- print ' Beginning to Decompression file from %s' % datetime.datetime.now()
- conm = 'bzip2 -dfk /data1/*%s*.bz2 && echo $?' % self.today
- bz = os.popen(conm).read().strip()
- if bz == '0':
- print ' Decompression file success %s' % datetime.datetime.now()
- else:
- print "\033[1;31;40m%s\033[0m" % "Decompression Error !"
- sys.exit()
- def restart_mysql(self):
- print "\033[1;32;40m%s\033[0m" % "Restart mysql Now,Please wait ...."
- os.popen("rm -rf /usr/local/mysql/etc/innodb.cnf && cp -f /data1/innodb.cnf /usr/local/mysql/etc/innodb.cnf")
- os.popen("sed -i 's/server-id = 1/server-id = 2/' /usr/local/mysql/etc/innodb.cnf")
- os.popen("/usr/local/mysql/bin/mysqladmin shutdown")
- os.popen("tar -zxvf /data1/mysql.tgz -C /")
- os.popen("rm -rf /home/mysql/data/*.info && rm -rf /home/mysql/data/ib_logfile*")
- os.popen("/usr/local/mysql/bin/mysqld_safe --defaults-file=/usr/local/mysql/etc/innodb.cnf --datadir=/home/mysql/data --user=mysql &")
- time.sleep(5)
- if os.popen("netstat -ntlp|grep 3306|wc -l").read().strip() == '0':
- print "\033[1;31;40m%s\033[0m" % "Mysql not Running,please start with '--skip-grant-tables' !"
- sys.exit()
- def import_date(self):#导入表结构和备份数据库
- print "\033[1;32;40m%s\033[0m" % "Slave import master date,Please wait ...."
- #导入表结构
- dir = '/data1/'
- table = 'table_%s' % self.today
- conm = "/usr/local/mysql/bin/mysql < %s%s && echo $?" % (dir,table)
- result = os.popen(conm).read().strip()
- if result == '0':
- print " Import %s success !" % table
- else:
- print "\033[1;31;40m%s\033[0m" % "Import Table structure Error !"
- sys.exit()
- for f in os.listdir(dir):#导入数据库
- if os.path.isfile(os.path.join(dir,f)) and (f.find('bz2') == -1) and (f.find('table') == -1):
- if f.find('adb') != -1:
- conm = "/usr/local/mysql/bin/mysql adb < %s && echo $?" % os.path.join(dir,f)
- result = os.popen(conm).read().strip()
- if result == '0':
- print " Import %s success !" % f
- else:
- print "\033[1;31;40m%s\033[0m" % "Import Database adb Error !"
- sys.exit()
- elif f.find('tdb') != -1:
- conm = "/usr/local/mysql/bin/mysql tdb < %s && echo $?" % os.path.join(dir,f)
- result = os.popen(conm).read().strip()
- if result == '0':
- print " Import %s success !" % f
- else:
- print "\033[1;31;40m%s\033[0m" % "Import Database tdb Error !"
- sys.exit()
- elif f.find('ddb') != -1:
- conm = "/usr/local/mysql/bin/mysql ddb < %s && echo $?" % os.path.join(dir,f)
- result = os.popen(conm).read().strip()
- if result == '0':
- print " Import %s success !" % f
- else:
- print "\033[1;31;40m%s\033[0m" % "Import Database ddb Error !"
- sys.exit()
- def slave_start(self):#启动salve
- print "\033[1;32;40m%s\033[0m" % "Settings Slave,Please wait ...."
- binlog,log_pos=self.bin_pos()
- sql = "change master to master_host='%s',master_user='repl',master_password='12341324',master_port=3306,master_log_file='%s',master_log_pos=%s;" % (self.host,binlog,log_pos)
- try:
- conn = MySQLdb.connect(host = '127.0.0.1',user = 'repl_monitor',passwd = 'sdfsdgfg',connect_timeout=5)
- cursor = conn.cursor(cursorclass = MySQLdb.cursors.DictCursor)
- #cursor.execute("slave stop;")
- cursor.execute(sql)
- cursor.execute("slave start;")
- cursor.execute("show slave status;")
- alldata = cursor.fetchall()[0]
- for key in alldata:
- print "%21s :" % key + '\t' + alldata[key]
- time.sleep(2)
- print "******************************************"
- cursor.execute("show slave status;")
- alldata = cursor.fetchall()[0]
- for key in alldata:
- print "%21s :" % key + '\t' + alldata[key]
- cursor.close()
- conn.close()
- except MySQLdb.Error,e:
- print e
- def bin_pos(self):#获取主库备份前的一个bin-log文件以及它的第一个pos位置
- today=datetime.date.today()
- yesterday = (today - datetime.timedelta(days=1)).strftime('%b %d')
- try:
- s=paramiko.SSHClient()
- s.set_missing_host_key_policy(paramiko.AutoAddPolicy())
- s.connect(self.host,self.port,self.user,self.password)
- conm = "ls -al /mysql_log/binlog|grep '%s'|tail -1|awk '{print $9}'" % yesterday
- stdin,stdout,stderr=s.exec_command(conm)
- binlog = stdout.read().strip()
- conm = "/usr/local/mysql/bin/mysqlbinlog /mysql_log/binlog/%s|grep log_pos|head -1|awk '{print $7}'" % binlog
- stdin,stdout,stderr=s.exec_command(conm)
- log_pos = stdout.read().strip()
- s.close()
- return binlog,log_pos
- except Exception,e:
- print "\033[1;31;40m%s\033[0m" % "SSH connect Error !"
- sys.exit()
- if __name__=="__main__":
- master_ip = raw_input('Enter :Mater_eth1_ip :')
- boss = Database(master_ip)
- boss.check_mysql()
- boss.export_table()
- boss.down_back()
- boss.unbz2()
- boss.import_date()
- boss.restart_mysql()
- boss.slave_start()
相关推荐
emmm00 2020-11-17
暗夜之城 2020-11-11
疯狂老司机 2020-09-08
王艺强 2020-11-17
aydh 2020-11-12
世樹 2020-11-11
zry 2020-11-11
URML 2020-11-11
spurity 2020-11-10
yifangs 2020-10-13
Andrea0 2020-09-18
Ida 2020-09-16
ltd00 2020-09-12
tufeiax 2020-09-03
xjd0 2020-09-10
greatboylc 2020-09-10
adsadadaddadasda 2020-09-08
CoderToy 2020-11-16
ribavnu 2020-11-16