shell 编程实战MySQL主从复制

MySQL主从架构脚本可以实现自动化安装、配置和管理。
shell脚本实现服务器MySQL一键YUM安装配置:
1、MySQL主库的操作:
主库上安装MySQL,设置server-id、bin-log;
授权复制同步的用户,对客户端授权;
确认bin-log文件名、position位置点。
2、MySQL从库的操作:
从库上安装MySQL,设置server-id;
changemaster指定主库和bin-log名以及position;
start slave 启动从库I/O线程;
show slave status\G查看主从的状态。
shell脚本实现服务器MySQL一键YUM安装配置,需要提前手动授权主库可以免密码登录从库服务器:
#!/bin/bash
#Auto install MySQL ABRepliation
#By author tang.com2018
#Define Path variables
MYSQL_SOFT="mysqlmysql-server mysql-devel mysql-libs php-mysql"
NUM=`rpm -qa |grep -imysql |wc -l`
INIT="/etc/init.d/mysqld"
CODE=$?
#MySQL To Install 2018
if [ $NUM -ne 0 -a -f$INIT ];then
echo-e "\033[32mThis Server Mysql already Install !\033[0m"
read-p "Please ensure yum remove Mysql Server,yes or no": INPUT
if [$INPUT == "y" -o $INPUT == "yes" ];then
yumremove $MYSQL_SOFT -y;rm -rf /var/lib/mysql /etc/my.cnf
yuminstall $MYSQL_SQFT -y
else
echo
fi
else
yumremove $MYSQL_SOFT -y;rm -rf /var/lib/mysql /etc/my.cnf
yuminstall $MYSQL_SOFT -y
if [$CODE -eq 0 ];then
echo-e "\033[32mThe Mysql Install Successfully !\033[0m"
else
echo-e "\033[32mThe Mysql Install Failed !\033[0m"
exit1
fi
fi
my_config(){
cat >/etc/my.cnf<<EOF
[mysqld]
datadir=/var/lib/mysql
socket=/var/lib/mysql/mysql.sock
user=mysql
symbolic-links=0
log-bin=mysql-bin
server-id=1
auto_increment_offset=1
auto_increment_increment=2
[mysqld_safe]
log-error=/var/log/mysqld.log
pid-file=/var/run/mysqld/mysqld.pid
EOF
}
my_config
/etc/init.d/mysqldrestart
ps -ef |grep mysql
MYSQL_CONFIG(){
#Master Config Mysql
mysql -e "grantreplication slave on *.* to 'slave_user'@'%' identified by '123456';"
MASTER_FILE=`mysql -e"show master status;"|tail -1 |awk '{print $1}'`
MASTER_POS=`mysql -e"show master status;"|tail -1|awk '{print $2}'`
MASTER_IPADDR=`ifconfig|grep "broadcast" |tail -1 |awk '{print $2}'`
read -p "PleaseInput Slave IPaddr : " SLAVE_IPADDR
#Slave Config Mysql
ssh -1 root$SLAVE_IPADDR "sed -i 's#server-id=1#server-id=2#g' /etc/my.cnf"
ssh -1 root$SLAVE_IPADDR "sed -i '/log-bin=mysql-bin/d' /etc/my.cnf"
ssh -1 root$SLAVE_IPADDR "/etc/init.d/mysqld restart"
ssh -1 root$SLAVE_IPADDR "mysql -e \"change master tomaster_host='$MASTER_IPADDR',master_user='slave_user',master_password='123456',master_log_file='$MASTER_FILE',master_log_pos='$MASTER_POS';\""
ssh -1 root$SLAVE_IPADDR "mysql -e \"slave start;\""
ssh -1 root$SLAVE_IPADDR "mysql -e \"show slave status\G;\""
}
read -p "Pleaseensure your Server is Master and you will config mysql Replication? yes orno": INPUT
if [ $INPUT =="y" -o $INPUT == "yes" ];then
MYSQL_CONFIG
else
exit0
fi