记得以前在服务器上安装 MySQL 安装过程中是会引导你设置 root 密码的,不知道从哪个版本起,可能是为了安全考虑,MySQL 的安装过程极为安静,会创建默认用户和随机密码,而不在安装时引导设定。另一个坑就是 plugins 字段的变化导致无法使用命令行密码登陆 root 用户,踩过多次坑之后记录一下,一并解决。

STEP 1. 安装

Ubuntu 上 apt 安装:sudo apt install mysql-server

2019/4/24,apt 软件源默认安装的版本是 5.7.25

SETP 2. 更改 root 用户密码

安装完成后 MySQL 会生成一个默认账号,在配置文件中查看用户名和密码

syf@syfs-server1 ~> sudo cat /etc/mysql/debian.cnf 
# 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

可以看到一个名为 debian-sys-maint 的本地用户,使用这个用户名和密码本地登录 MySQL 后修改root 用户密码、加密插件和允许登陆的主机:

syf@syfs-server1 ~> mysql -udebian-sys-maint -p
Enter password: 
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 3
Server version: 5.7.25-0ubuntu0.18.04.2 (Ubuntu)

Copyright (c) 2000, 2019, Oracle and/or its affiliates. All rights reserved.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql> use mysql;
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A

Database changed
mysql> update user set plugin="mysql_native_password", authentication_string=password("your_passwd_here"), Host="%" where User="root";
Query OK, 1 row affected, 1 warning (0.00 sec)
Rows matched: 1  Changed: 1  Warnings: 1

mysql> flush privileges;
Query OK, 0 rows affected (0.00 sec)

至此就可以使用 Navicat 或者 MySQL-Front 等工具远程登陆 MySQL 了。

为了安全起见,还是建议设置强密码,且仅允许本地登录。

标签: linux, mysql

添加新评论