MySQL(MariaDB)默认密码和修改方法

由于笔者只测试过Ubuntu 16.04.4、Ubuntu 19.04和Debian 9,此方法不确定在其他版本下适用。

本文章介绍的方法同样适用于这样的错误信息。

➜ ~ mysql -u root -p
Enter password:
ERROR 1698 (28000): Access denied for user 'root'@'localhost'


## 查看默认密码
某些发行版本,使用包管理器安装MySQL后,查看这个文件可以看到安装后的默认密码`/etc/mysql/debian.cnf`,这个密码是属于`debian-sys-maint`的,而非`root`。
即使在这里你可能可以使用root用户登录,因为root用户默认登录方式是使用socket连接,而不验证密码。

## 修改root密码
如果需要修改先使用`debian-sys-maint`登录数据库,完成以下操作
1. `select user, plugin from mysql.user;`查看默认的连接方式。
2. 如果是`auth_socket`(MySQL)的连接方式,则继续下面得步骤,如果是`unix_socket`(MariaDB),则转到**MariaDB的处理方法**。
3. `update mysql.user set authentication_string=password('root'), plugin = 'mysql_native_password' where user = 'root';`使用这一行明令将root密码修改为root。
4. `flush privileges;`应用权限。
5. 退出并重启MySQL。

## MariaDB的处理方法
上面的方法仅针对MySQL测试。
MariaDB的root默认连接方式是`unix_socket`(MariaDB)
在Debian中软件包mysql已经替换成了mariadb了。在安装后`/etc/mysql/debian.cnf`预设了root用户使用socket的连接方式,所以不输入密码也可在命令行直接使用mysql命令登录。
要想使用密码连接需要修改连接方式
1. 输入mysql进入客户端,若无法进入则跳过。
2. 输入`select user, plugin from mysql.user`查看默认的连接方式。
3. 如果是`unix_socket`(MariaDB),则继续下面得步骤。
4. 退出mysql,并kill掉进程。
5. 打开`mysqld_safe --skip-grant-tables`放入后台,并进入`mysql`。
6. `update mysql.user set authentication_string = password('root'), plugin = 'mysql_native_password' where user = 'root';`。
7. `flush privileges;`应用权限。
8. 修改`/etc/mysql/mariadb.conf.d/50-server.cnf`中的`bind-address`为允许的网络地址,若为整个网络则填入`0.0.0.0`或注释掉
9. 重启服务
10. 退出并重启MySQL。

## 为MySQL添加远程访问
1. 修改`/etc/mysql/mysql.conf.d/mysqld.cnf``/etc/mysql/my.cnf`中的`bind-address`为允许的网络地址,若为整个网络则填入`0.0.0.0`或注释掉
2. 重启服务
3. 启动mysql,输入`use mysql;`进入mysql表
4. 修改地址`grant all privileges on *.* to 'root'@'%' identified by 'root' with grant option;`允许root用户远程使用root为密码连接。
5. 使修改生效`flush privileges;`
6. 退出MySQL。
原文地址:https://www.cnblogs.com/zhuxiaoxi/p/10843659.html