1、通过rpm包安装mysql5.7、expect、mysql server
通过MySQL官方的 Yum Repository 安装MySQL
安装 expect(下面的sh文件执行时依赖expect,需在server之前安装)
yum install -y http://dev.mysql.com/get/mysql57-community-release-el7-10.noarch.rpm yum install -y http://mirror.centos.org/centos/7/os/x86_64/Packages/expect-5.45-14.el7_1.x86_64.rpm yum install -y mysql-community-server
若因网络问题安装失败可以尝试再次执行
例:
2、启动mysql服务并设置开机自启动
systemctl start mysqld.service systemctl enable mysqld.service
3、设置自定义密码
创建一个sh文件,内容写入:(变量newpassword为要定义的密码,默认为root)
#!/bin/bash password=$(grep 'temporary password' /var/log/mysqld.log | awk -F 'localhost: ' '{print $2;}') newpassword=root # <--password expect <<EOF spawn mysql -uroot -p expect "password" send "${password}\n" expect "mysql>" send "set global validate_password_policy=0;\n" expect "mysql>" send "set global validate_password_length=1;\n" expect "mysql>" send "ALTER USER 'root'@'localhost' IDENTIFIED BY \"${newpassword}\";\n" expect "mysql>" send "use mysql;\n" expect "mysql>" send "update user set host='%' where user='root' and host='localhost';\n" expect "mysql>" send "flush privileges;\n" expect eof EOF
例:
注解:
获取MySQL默认的密码:grep 'temporary password' /var/log/mysqld.log | awk -F 'localhost: ' '{print $2;}'
关闭密码必须含有大小写字母数字和特殊字符的限制:validate_password_policy=0
关闭密码长度限制:validate_password_length=1
允许被外部访问:update user set host='%' where user='root' and host='localhost';