使用python3腳本部署mariadb主從架構

環境準備

一個腳本自動部署master服務mysql

另外一個部署slave服務linux

 關閉主從節點的防火牆sql

以及事先設置好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節點會變更,特別時重啓數據庫後。ssh

若是查看slave status,顯示:ide

  Slave_IO_Running: No
 Slave_SQL_Running: No

spa

或者一個YES一個connecting的話,這是由於主節點的master狀態發生了變化或者兩臺主機的某一臺防火牆沒有關閉。rest

 

複製代碼
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)
 
複製代碼

 

若是報錯:code

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

緣由二: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

 

相關文章
相關標籤/搜索