AI智能
改变未来

91.mysql主从配置自动部署

#!/bin/bash#The script is used for master-slave configuration.#Date 2021-02-21master_ip=192.168.32.1slave_ip=192.168.32.2mysql=\"/usr/local/mysql/bin/mysql -uroot -ppassword\"my_cnf=/etc/my.cnfmaster_dir=/tmp/mysql_slavepass=\"hSlneoT03j\"#检测命令是否执行成功check_ok() {if [ $? -ne 0 ];thenecho \"$1 command is error.\"exit 1fi}#检测文件是否存在file_exist() {d=`date +%F-%T`if [ -f $1 ];thenmv $1 $1_$dfi}#判断是否含有serve-id配置项,无则添加if ! grep \'^server-id\' $my_cnf;thensed -i \'/^\\[mysqld\\]$/a\\server-id = 1001\' $my_cnffi#判断是否含有log-bin配置项,无则添加if ! grep \'^log-bin.*=.*\' $my_cnf;thensed -i \'/^\\[mysqld\\]$/a\\log-bin = maria_bin\' $my_cnffi#判断是否含有binlog-ignore-db配置项,无则添加if ! grep \'^binlog-ignore-db\'  $my_cnf;thensed -i \'/^log-bin.*/a\\binlog-ignore-db = mysql\' $my_cnffi#重启mysql服务systemctl restart mysql#检测是否重启成功check_ok \"restart mysql\"#EOF赋值mysql从库账号密码$mysql << EOFgrant 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.logfile=`tail -1 $master_dir/master.log |awk \'{ print $1}\'`pos=`tail -1 $master_dir/master.log |awk \'{print $2}\'`#判断文件是否存在file_exist $master_dir/slave.sha=\'EOF\'#定义变量#从库shell脚本cat > $master_dir/slave.sh <<EOF#!/bin/bashcheck_ok() {if [ $? -ne 0 ];thenecho \"$1 command is error.\"exit 1fi}#判断my.cnf文件是否包含server-id配置项,无则添加if ! grep \'^server-id\' /etc/my.cnf;thensed -i \'/\\[mysqld\\]$/a\\server-id = 1002\' /etc/my.cnffi#重启服务systemctl restart mysqlcheck_ok \"slave mysql restart\"$mysql <<EOFstop 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/expectset passwd \"password\"spawn rsync -a $master_dir/slave.sh root@$slave_ip:/tmp/slave.shexpect {\"yes/no\" { send \"yes\\r\"}\"password:\"{ send \"\\$passwd\\r\"}}expect eofEOF#rs_slave.expect文件给予执行权限chmod +x $master_dir/rs_slave.expect$master_dir/rs_slave.expectcheck_ok \"rysnc\"#检测文件是否存在file_exist $master_dir/exe.expect#内嵌expect交互脚本执行命令cat > $master_dir/exe.expect <<EOF#!/usr/bin/expectset password \"password\"spawn ssh root@$slave_ipexpect {\"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.expectcheck_ok \"exe.expect excute“#主库解除锁表$mysql -e \"unlock tables\"
赞(0) 打赏
未经允许不得转载:爱站程序员基地 » 91.mysql主从配置自动部署