解决安装MySQL时没有设置root密码的问题

建立LNMP环境时,安装MySQL的命令为

1
2
3
4
5
apt install php7.2-mysql
wget http://repo.mysql.com/mysql-community-release-el7-5.noarch.rpm
rpm -ivh mysql-community-release-el7-5.noarch.rpm
apt update
apt install mysql-server

正常来说安装过程中会弹出设置root密码,但命令直接运行到底也没弹出。

使用:

1
mysqladmin --version

返回信息:

1
mysqladmin  Ver 8.42 Distrib 5.7.26, for Linux on x86_64

说明安装MySQL成功。

既然安装成功了,就自己设置数据库的root密码呗。

执行命令:

1
mysqladmin -u root password "new_password";

但却返回信息:

1
2
mysqladmin: [Warning] Using a password on the command line interface can be insecure.
Warning: Since password will be sent to server in plain text, use ssl connection to ensure password safety.

大致意思是“在命令行界面上使用密码可能不安全。由于密码将以纯文本形式发送到服务器,因此请使用ssl连接以确保密码安全。”

那好吧。只能这样了。通过sudo -u root -p进行免密登录,进入MySQL后再进行密码修改。

1
2
3
update mysql.user set plugin="mysql_native_password" where user="root";

update mysql.user set authentication_string=password('new_password') where user='root’and Host = ‘localhost’;

然后使用\q或者exit退出MySQL。

使用service mysql restart重启MySQL,使用mysql -uroot -p登录MySQL的root账户。和Linux登录一样,不显示密码。输错的话会进不去,不会再和之前没设密码一样随便输入都可以进入。密码即为之前设置的new_password。

参考方法