Ubuntu 使用 apt 新装 MySQL 设置 root 密码

按照网上的一些教程安装 MySQL 时,Ubuntu 18.04 服务器在 APT-GET 安装 MySQL-server 期间并没有要求设置 MySQL 的 root 用户密码。

新的 ubuntu 自带的 MySQL 禁用了 root 账户,密码存放在以下:

1
sudo vim /etc/mysql/debian.cnf

用户名默认的不是 root,而是 debian-sys-maint,如下所示

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
# Automatically generated for Debian scripts. DO NOT TOUCH!
[client]
host     = localhost
user     = debian-sys-maint
password = ********
socket   = /var/run/mysqld/mysqld.sock
[mysql_upgrade]
host     = localhost
user     = debian-sys-maint
password = ********
socket   = /var/run/mysqld/mysqld.sock

使用上述文件内提供的账号和密码即可登录,建议最好运行 mysql_secure_installation using 对 MySQL 初始化

1
sudo mysql_secure_installation

如果以上还不能解决,那么可以使用以下命令登录 MySQL

1
mysql -u debian-sys-maint -p

系统会提示输入密码,登陆成功后,我们手动设置 root 密码

1
update mysql.user set authentication_string=password('**************') where user='root' and Host = 'localhost';

如果提示

1
2
Query OK, 1 row affected, 1 warning (0.01 sec)
Rows matched: 1  Changed: 1  Warnings: 1

说明已经修改成功,使用下面指令进行测试

1
2
3
4
5
flush privileges;
quit
sudo service mysql restart
sudo mysql -u root -p
exit

希望这能对大家有所帮助。