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

环境准备

一个脚本自动部署master服务

另一个部署slave服务

 关闭主从节点的防火墙

master

import paramiko
def master(): ssh
=paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh.connect(hostname='192.168.253.168',port=22,username='root',password='369369ynx') stdin,stdout,stderr = ssh.exec_command("sed -i -e '12aserver_id=1' -e '13alog_bin=mysql_bin' /etc/my.cnf.d/server.cnf") stderr,stdin,stdout=ssh.exec_command('systemctl restart mariadb') stderr,stdin,stdout=ssh.exec_command("mysql -uroot -p1 -e 'CREATE USER 'slave'@'%' IDENTIFIED BY 'slave';") stderr,stdin,stdout = ssh.exec_command('''mysql -uroot -p1 -e "grant replication slave on *.* to 'slave'@'%' identified by 'slave'"''') stderr,stdin,stdout=ssh.exec_command('''mysql -uroot -p1 -e "show master status" ''') master()


在linux端查看是否配置成功。并且根据这两个变量来设置slave。


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

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

slave

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

如果查看slave status,显示:

  Slave_IO_Running: No
 Slave_SQL_Running: No

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

ip='192.168.253.168'
file='mysql_bin.000012'
port=29809
import paramiko
def slave():
    ssh = paramiko.SSHClient()
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    ssh.connect(hostname='192.168.253.190', port=22, username='root', password='369369ynx')
    slave1 = ssh.exec_command("sed -i -e '12aserver_id=2' /etc/my.cnf.d/server.cnf")
    stderr,stdin,stdout=ssh.exec_command('systemctl restart mariadb')
    slave2 = ssh.exec_command('''mysql -uroot -p1 -e "CHANGE MASTER TO MASTER_HOST=%s, MASTER_USER='slave', MASTER_PASSWORD='slave', MASTER_PASSWORD='slave', MASTER_LOG_FILE=%s, MASTER_LOG_POS=%s; "''' % (ip,file,port))
    slave3=ssh.exec_command("mysql -uroot -p1 -e 'start slave;'")
slave()

结果显示:

检测:

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

master 

slave

 

猜你喜欢

转载自www.cnblogs.com/zzzynx/p/11125892.html