使用python3脚本部署mariadb主从架构

环境准备

一个脚本自动部署master服务

另一个部署slave服务

 关闭主从节点的防火墙

以及事先设置好root远程登陆的权限。

master

复制代码
import paramiko
ssh=paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(hostname='192.168.253.180',port=22,username='root',password='369369yn')
for i in ["sed -i -e '12aserver_id=1' -e '13alog_bin=mysql_bin' /etc/my.cnf.d/server.cnf" , 'systemctl restart mariadb' , '''mysql -uroot -p1 -e "grant replication slave on *.* to 'slave'@'%' identified by 'slave'"''' ,'''mysql -uroot -p1 -e "show master status" ''']:
print(i)

stdin,stderr,stdout=ssh.exec_command(i)
res = stdout.read().decode('utf-8') + stderr.read().decode('utf-8')
print(res)
运行显示结果:
sed -i -e '12aserver_id=1' -e '13alog_bin=mysql_bin' /etc/my.cnf.d/server.cnf
systemctl restart mariadb
mysql -uroot -p1 -e "grant replication slave on *.* to 'slave'@'%' identified by 'slave'"
mysql -uroot -p1 -e "show master status"
File    Position    Binlog_Do_DB    Binlog_Ignore_DB
mysql_bin.000012   887359 
复制代码


linux端查看是否配置成功。



注:mysql -uroot -p1 -
e   此命令可以使用paramiko模块直接执行sql语句。eedit的意思。

当然,也可以使用pymsql模块连接mysql数据库然后利用cur游标里封装的execute方法来执行sql语句,但是可能在执行给与权限的命令时会报错,因为远程登陆并没有权限这么做。

slave

如下的file变量和port变量在master节点会变动,特别时重启数据库后。

如果查看slave status,显示:

  Slave_IO_Running: No
 Slave_SQL_Running: No

或者一个YES一个connecting的话,这是因为主节点的master状态发生了变化或者两台主机的某一台防火墙没有关闭。

复制代码
master_ip = '192.168.253.168'
log_file='mysql_bin.000012'
pos=887350
import paramiko
ssh=paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(hostname='192.168.253.30',port=22,username='root',password='369369ynx')
for i in ["sed -i '12aserver_id=2' /etc/my.cnf.d/server.cnf",'systemctl restart mariadb' , '''mysql -uroot -p1 -e "CHANGE MASTER TO MASTER_HOST='%s', MASTER_USER='slave', MASTER_PASSWORD='slave', MASTER_LOG_FILE='%s', MASTER_LOG_POS=%s" ''' % (master_ip,log_file,pos) , "mysql -uroot -p1 -e 'start slave'"]:
print(i)
stdin,stderr,stdout=ssh.exec_command(i)
res = stdout.read().decode('utf-8') + stderr.read().decode('utf-8')
print(res)
 
复制代码

如果报错:

The server is not configured as slave; fix in config file or with CHANGE MASTER TO
原因一:配置文件没有添加server_id=2,或者添加完没有成功

原因二:mysql -uroot -p1 -e "CHANGE MASTER TO MASTER_HOST='%s', MASTER_USER='slave', MASTER_PASSWORD='slave', MASTER_LOG_FILE='%s', MASTER_LOG_POS=%s" ''' % (master_ip,log_file,pos)

这条命令没有执行成功,但注意这条命令不成功不会报错,怎么检测呢,可以粘贴脚本的这条命令到终端上执行试试看能否成功。

结果显示:

检测:

在主节点创建一个数据库,并在从节点数据库中查看是否同步上。

master 

slave

 

原文地址:https://www.cnblogs.com/daisyyang/p/11137438.html