欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

mysql5.7 on centos7上使用systemctl管理多个端口及创建多个端口的脚本(代码实现)

程序员文章站 2022-04-12 21:20:41
mysql5.7 on centos7上使用systemctl管理多个端口及创建多个端口的脚本(代码实现)。 #!/bin/bash #Usage: bash instal...

mysql5.7 on centos7上使用systemctl管理多个端口及创建多个端口的脚本(代码实现)。

#!/bin/bash
#Usage: bash install_different_port_for_mysql5.7.sh 9999
#
source /etc/profile
let portn=$1
if [ x"${portn}" == "x" ]; then
   echo "Usage: ./install_different_port_for_mysql5.7.sh portnum"
   exit 1
fi

##检查目标端口是否有已经占用 ps -ef|grep mysql|grep 9999  or netstat -anltp|grep 9999 or lsof -i :9999
lsof -i :${portn}
if [ $? -eq 0 ]; then
   echo "Port ${portn} has been used,please change a port : lsof -i :${portn}"
   exit 1
fi

if [ -d /mysql${portn} ]; then
   echo "Port ${portn} has been used,please change a port : /mysql${portn} has been exis"
   exit 1
fi

cat /etc/my.cnf | grep "${portn}"
if [ $? -eq 0 ]; then
   echo "Port ${portn} has been used,please change a port : port ${portn} has been used in /etc/my.cnf"
   exit 1
fi

##创建目录
mkdir -p /mysql${portn}/{mycnf,socket,pid,data,log}
chown -R mysql.mysql /mysql${portn}/*

##备份my.cnf文件
cp /etc/my.cnf /etc/my.cnf_oldbak

##修改my.cnf文件
cat >> /etc/my.cnf <<EOF

##for mysql port  ${portn}
[mysqld@${portn}]
datadir=/mysql${portn}/data
socket=/mysql${portn}/socket/mysql${portn}.sock
port = ${portn}
log-error=/mysql${portn}/log/error${portn}.log
pid-file=/mysql${portn}pid/mysqld${portn}.pid

EOF

##初始化新的端口
mysqld --initialize --user=mysql --datadir=/mysql${portn}/data



##touch日志文件
touch /mysql${portn}/log/slow${portn}.log
touch /mysql${portn}/log/error${portn}.log
chown -R mysql.mysql /mysql${portn}/log/*.log

##启动端口
systemctl start mysqld@${portn}

##获得新初始化端口root的临时密码
passwdtemp=`cat /var/log/mysqld.log|grep "temporary password"|tail -n1|awk '{print $NF}'`

##修改root的密码
pssroot="Root#2000"
mysql -uroot -p$passwdtemp -S /mysql${portn}/socket/mysql${portn}.sock --connect-expired-password -e "Set password=password('${pssroot}');Alter user 'root'@'localhost' password expire never;CREATE USER 'root'@'%' IDENTIFIED BY '${pssroot}'; GRANT ALL PRIVILEGES ON *.* TO 'root'@'%' WITH GRANT OPTION; GRANT ALL PRIVILEGES ON *.* TO 'root'@'localhost' WITH GRANT OPTION; Flush privileges;create database test_demo;exit"

ls -lrth /mysql${portn}/data/

##检查systemctl的状态 并且设置为enable
systemctl status mysqld@${portn}