MySQL数据库自动生成并修改随机root密码的脚本

在MySQL数据库部署的过程中,在安装了MySQL软件,并配置了my.cnf配置文件后,需要创建MySQL实例。

MySQL 5.5实例创建完成了,默认会有登陆用户名和密码为空的用户,一般需要修改root用户密码,并删除无效用户,然后才能提供给应用使用。

这个过程可以通过shell脚本自动完成实例创建,启动,自动生成密码,修改root用户密码,删除无效用户。

shell脚本有多种编写方法,我编写的shell脚本如下:

#!/bin/bash

# this scripts used to initial the mysql instance and modify password
# created by zhaofx


# MySQL software directory.
readonly SYMLINK='/usr/local/mysql'
echo "MySQL的软件安装目录为${SYMLINK}"

# MySQL database port
readonly MYSQL_PORT=3306
echo "MySQL实例的端口为${MYSQL_PORT}"

# MySQL database directory.
readonly MYSQL_DATA_DIR="/data/mysql_${MYSQL_PORT}"
echo "MySQL的实例数据文件目录为${MYSQL_DATA_DIR}"


echo "准备创建MySQL实例"
cd $SYMLINK
./scripts/mysql_install_db --user=mysql --basedir=/usr/local/mysql --datadir=${MYSQL_DATA_DIR}/data

echo "开始启动数据库实例,修改root用户密码,删除无效用户"
echo ""
cp /etc/my.cnf /data/mysql_${MYSQL_PORT}/my.cnf
echo "Startup MySQl Service:localhost_"${MYSQL_PORT}
/usr/local/mysql/bin/mysqld_safe --defaults-file=/data/mysql_${MYSQL_PORT}/my.cnf &
echo ""

# MySQL root password
# 随机生成八位密码,作为MySQL的密码
for i in {1..10}
do
A=`head -c 500 /dev/urandom | tr -dc a-zA-Z | tr [a-z] [A-Z]|head -c 1`
B=`head -c 500 /dev/urandom | tr -dc a-z0-9A-Z | head -c 6`
C=`echo $RANDOM|cut -c 2`
echo $A$B$C > /home/mysql/.password_mysql
done

readonly MYSQL_ROOT_PASS=$A$B$C
echo "MySQL实例的root用户密码已经生成"

su - mysql <<EOF
/usr/local/mysql/bin/mysql -uroot -S /data/mysql_${MYSQL_PORT}/tmp/mysql.sock -e "select user,host from mysql.user;"
/usr/local/mysql/bin/mysqladmin -uroot -S /data/mysql_${MYSQL_PORT}/tmp/mysql.sock password "${MYSQL_ROOT_PASS}"
EOF
echo "MySQL的root用户密码已经修改"
echo ""
   
/usr/local/mysql/bin/mysql -uroot -p${MYSQL_ROOT_PASS} -S /data/mysql_${MYSQL_PORT}/tmp/mysql.sock -e "delete from mysql.user where user='';delete from mysql.user where user='root' and host!='localhost'; FLUSH PRIVILEGES;"
/usr/local/mysql/bin/mysql -uroot -p${MYSQL_ROOT_PASS} -S /data/mysql_${MYSQL_PORT}/tmp/mysql.sock -e "delete from mysql.db where db='test' or db='test\\_%'; FLUSH PRIVILEGES;"
echo "MySQL实例启动成功,初始用户环境修改完毕"
echo ""

/usr/local/mysql/bin/mysql -uroot -p${MYSQL_ROOT_PASS} -S /data/mysql_${MYSQL_PORT}/tmp/mysql.sock -e " show databases;"
/usr/local/mysql/bin/mysql -uroot -p${MYSQL_ROOT_PASS} -S /data/mysql_${MYSQL_PORT}/tmp/mysql.sock -e " select user,host from mysql.user;"

大家可以参考!

相关推荐