您的位置:首页 > 其它

主从同步自动化脚本

2016-09-07 22:09 393 查看
#!/bin/bash
# AB replication自动配置脚本
# 20160901 Booboo Wei
# 执行该脚本需要设置无密钥登陆,例如教学环境中,我在workstation上跑该脚本,那么需要在workstation和主服务器mastera上执行一下操作
# 无密钥登陆
#ssh-keygen
#for i in `seq 10 15`;do ssh-copy-id root@172.25.X.$i;done
IPT(){
if [[ $1 =~ ^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$ ]]
then
IP=(${1//./ })
[ ${IP[0]} -gt 0 -a ${IP[0]} -lt 255 ] && [ ${IP[1]} -ge 0 -a ${IP[1]} -lt 255 ] && [ ${IP[2]} -ge 0 -a ${IP[2]} -lt 255 ] && [ ${IP[3]} -gt 0 -a ${IP[3]} -lt 255 ] && echo yes || echo no
else
echo no
fi
}

INSTALL () {
#read -p 'plz input slave ip: ' ip
#read -p 'plz input software name: ' pack
if [ `IPT $sip` = yes ]
then
ssh root@"$sip" "yum install -y $pack"
fi
}

MASTER () {
#read -p 'plz input master-ip :' mip
#read -p 'plz input slave-ip: ' sip
#read -p 'plz input root-password :' password
if [ `IPT $mip` = yes ]
then
ssh root@"$mip" "grep server-id /etc/my.cnf" ||  ssh root@"$mip" "sed -i '/\[mysqld\]/aserver-id=1' /etc/my.cnf"
if	ssh root@"$mip" "grep log-bin /etc/my.cnf"
then
echo log-bin ok
else
ssh root@"$mip" "sed -i '/\[mysqld\]/alog-bin=/var/lib/mysql-log/mastera' /etc/my.cnf" && ssh root@"$mip" "mkdir /var/lib/mysql-log/;chown mysql. /var/lib/mysql-log/;systemctl restart mariadb"
fi
ssh root@"$mip" "setenforce 0 ;systemctl stop firewalld"
ssh root@"$mip" "mysqldump -uroot -p$password -A --single-transaction --master-data=2 --flush-logs > /tmp/`date +%m%d%H`;scp /tmp/`date +%m%d%H` root@$sip:/tmp"
cat >/tmp/gg << ENDF
grant replication slave on *.* to slave@$sip identified by 'uplooking';
flush privileges;
ENDF
scp /tmp/gg root@"$mip":/tmp
ssh root@"$mip" "mysql -uroot -p$password < /tmp/gg"

fi
}

SLAVE(){
#read -p 'plz input master-ip :' mip
#read -p 'plz input slave ip :' sip
#read -p 'plz input root-password :' password
ssh root@"$sip" "systemctl stop mariadb;rm -rf /var/lib/mysql/*"

ssh root@"$sip" "sed -n '22p' /tmp/`date +%m%d%H`>/tmp/cc;cut -d ' ' -f 5 /tmp/cc;cut -d ' ' -f 6 /tmp/cc" >/tmp/ml

ssh root@"$sip" "grep server-id /etc/my.cnf" ||  ssh root@"$sip" "sed -i '/\[mysqld\]/aserver-id=3' /etc/my.cnf"
ssh root@"$sip" "setenforce 0 ;systemctl stop firewalld;systemctl restart mariadb;systemctl status mariadb"
cat > /tmp/ss <<ENDF
change master to master_host='$mip',master_user='slave',master_password='uplooking',
start slave;
ENDF

sed -i '1r /tmp/ml' /tmp/ss
scp /tmp/ss root@"$sip":/tmp
ssh root@"$sip" "mysql < /tmp/`date +%m%d%H`"
ssh root@"$sip" "echo flush privileges|mysql"
ssh root@"$sip" "mysql -uroot -p$password < /tmp/ss"
ssh root@"$sip" "echo show slave status'\G'|mysql -uroot -p$password"

}

read -p 'plz input master-ip :' mip
read -p 'plz input slave ip :' sip
read -p 'plz input root-password :' password
read -p 'plz input software name: ' pack
INSTALL
MASTER
SLAVE
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: