#!/bin/bash #The script is used for master-slave configuration. #Date 2021-02-21 master_ip=192.168.32.1 slave_ip=192.168.32.2 mysql="/usr/local/mysql/bin/mysql -uroot -ppassword" my_cnf=/etc/my.cnf master_dir=/tmp/mysql_slave pass="hSlneoT03j" #檢測命令是否執行成功 check_ok() { if [ $? -ne 0 ];then echo "$1 command is error." exit 1 fi } #檢測文件是否存在 file_exist() { d=`date +%F-%T` if [ -f $1 ];then mv $1 $1_$d fi } #判斷是否含有serve-id配置項,無則添加 if ! grep '^server-id' $my_cnf;then sed -i '/^\[mysqld\]$/a\server-id = 1001' $my_cnf fi #判斷是否含有log-bin配置項,無則添加 if ! grep '^log-bin.*=.*' $my_cnf;then sed -i '/^\[mysqld\]$/a\log-bin = maria_bin' $my_cnf fi #判斷是否含有binlog-ignore-db配置項,無則添加 if ! grep '^binlog-ignore-db' $my_cnf;then sed -i '/^log-bin.*/a\binlog-ignore-db = mysql' $my_cnf fi #重啓mysql服務 systemctl restart mysql #檢測是否重啓成功 check_ok "restart mysql" #EOF賦值mysql從庫帳號密碼 $mysql << EOF grant replication slave on *.* to 'repl'@$slave_ip identified by '$pass'; flush tables with read lock; EOF #判斷是否有該存放目錄 [ -d $master_dir ] || mkdir -p $master_dir #將master兩個參數File和Position存放至master.log $mysql -e "show master status" > $master_dir/master.log file=`tail -1 $master_dir/master.log |awk '{ print $1}'` pos=`tail -1 $master_dir/master.log |awk '{print $2}'` #判斷文件是否存在 file_exist $master_dir/slave.sh a='EOF'#定義變量 #從庫shell腳本 cat > $master_dir/slave.sh <<EOF #!/bin/bash check_ok() { if [ $? -ne 0 ];then echo "$1 command is error." exit 1 fi } #判斷my.cnf文件是否包含server-id配置項,無則添加 if ! grep '^server-id' /etc/my.cnf;then sed -i '/\[mysqld\]$/a\server-id = 1002' /etc/my.cnf fi #重啓服務 systemctl restart mysql check_ok "slave mysql restart" $mysql <<EOF stop slave; change master to master_host="$master_ip",master_user='repl',master_password="$pass", master_log_file="$file",master_log_pos=$pos; start slave; $a#內嵌不能雙EOF,用變量代替 EOF #檢測文件是否存在 file_exist $master_dir/rs_slave.expect #內嵌expect交互腳本將slave.sh傳輸至從庫 cat > $master_dir/rs_slave.expect <<EOF #!/usr/bin/expect set passwd "password" spawn rsync -a $master_dir/slave.sh root@$slave_ip:/tmp/slave.sh expect { "yes/no" { send "yes\r"} "password:"{ send "\$passwd\r"} } expect eof EOF #rs_slave.expect文件給予執行權限 chmod +x $master_dir/rs_slave.expect $master_dir/rs_slave.expect check_ok "rysnc" #檢測文件是否存在 file_exist $master_dir/exe.expect #內嵌expect交互腳本執行命令 cat > $master_dir/exe.expect <<EOF #!/usr/bin/expect set password "password" spawn ssh root@$slave_ip expect { "yes/no"{ send "yes\r"} "password:"{ send "\$password\r" } } expect "]*" send "/bin/bash /tmp/slave.sh\r" expect "]*" send "exit\r" EOF #exe.expect文件給予執行權限 chmod +x $master_dir/exe.expect $master_dir/exe.expect check_ok "exe.expect excute「 #主庫解除鎖表 $mysql -e "unlock tables"