環境准備
一個腳本自動部署master服務
另一個部署slave服務
關閉主從節點的防火牆
以及事先設置好root遠程登陸的權限。
grant all on *.* to root@'%' identified by 'root' ;
master
import paramiko
ssh=paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(hostname='192.168.253.168',port=22,username='root',password='root')
a="sed -i -e '12aserver_id=1' -e '13alog_bin=mysql_bin' /etc/my.cnf.d/server.cnf"
b= 'systemctl restart mariadb'
c='''mysql -uroot -proot -e "grant replication slave on *.* to 'slave'@'%' identified by 'slave'"'''
d='''mysql -uroot -proot -e "show master status" '''
當然也可以將abcd四條命令寫入一個列表,使用for語句循環出來放入下面命令執行。
stdin,stderr,stdout=ssh.exec_command(d) #將abcd分別執行
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 887350
在linux端查看是否配置成功。
注: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狀態發生了變化或者兩台主機的某一台防火牆沒有關閉。
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.167',port=22,username='root',password='root')
a="sed -i '12aserver_id=2' /etc/my.cnf.d/server.cnf"
b='systemctl restart mariadb'
c='''mysql -uroot -proot -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)
d="mysql -uroot -proot -e 'start slave'"
stdin,stderr,stdout=ssh.exec_command(d) #將abcd分別執行
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