新版mysql里自动为root用户启动了新的登录验证插件 auth_socket , 可以通过以下命令查看
1
2
3
4
5
6
7
8
9
10
11
|
mysql> select host,user,plugin from mysql.user;
+-----------+------------------+-----------------------+
| host | user | plugin |
+-----------+------------------+-----------------------+
| localhost | debian-sys-maint | caching_sha2_password |
| localhost | mysql.infoschema | caching_sha2_password |
| localhost | mysql.session | caching_sha2_password |
| localhost | mysql.sys | caching_sha2_password |
| localhost | root | auth_socket |
+-----------+------------------+-----------------------+
6 rows in set (0.00 sec)
|
auth_socket插件的优势总结起来以下几点:
- 仅能通过unix套接字登录mysql, 可以保证root@localhost账户只能通过mysql所在机器的mysql客户端访问
- 登录mysql的用户, 必须与当前系统用户名一致, 如果不一致, 则拒绝访问
解决方案
如果确实希望通过非root用户可以通过root账户访问mysql, 可以修改root@localhost账户的验证插件为mysql的内置认证插件mysql_native_password
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
|
mysql> update mysql.user set plugin='mysql_native_password' where user='root';
Query OK, 2 rows affected (0.00 sec)
Rows matched: 2 Changed: 2 Warnings: 0
mysql> select host,user,plugin from mysql.user;
+-----------+------------------+-----------------------+
| host | user | plugin |
+-----------+------------------+-----------------------+
| localhost | debian-sys-maint | caching_sha2_password |
| localhost | mysql.infoschema | caching_sha2_password |
| localhost | mysql.session | caching_sha2_password |
| localhost | mysql.sys | caching_sha2_password |
| localhost | root | mysql_native_password |
+-----------+------------------+-----------------------+
6 rows in set (0.00 sec)
mysql> flush privileges;
Query OK, 0 rows affected (0.00 sec)
mysql> exit
# 切换到普通用户
$ su loki
# 此时可以用普通用户使用mysql的root账户登录了
$ mysql -u root
|
但通常不建议这么做, root@localhost 是最终管理mysql的用户, 非必要不会在业务中使用
设置其他机器远程ssh登录
远程登录需要目标机器安装有openssh-server, ubantu此版本默认只安装了openssh-client, 需要自己安装openssh-server
1
2
3
4
|
# 切换到root用户 , 或者后续命令添加sudo前缀
su -
$ apt install openssh-server -y
|
打开/etc/ssh/sshd_config文件, 添加如下语句,
1
2
|
# 允许root用户通过ssh的方式登录本机
PermitRootLogin yes
|
关于PermitRootLogin的文档可以参考官方文件
为mysql创建一个新的root账户
这个账户依然是通过root访问, 但是目的是为了设置通过其他host访问时, 必须通过输入密码的方式进行访问
1
2
3
4
5
6
7
8
9
10
11
|
# 切换到root用户
$ su -
# 这里我已经把root@localhost的访问认证方式重新改回了auth_socket, 所以只能通过ubantu的root用户访问
$ mysql -u root
# 创建允许其他host访问的root用户, 这个用户的默认登录认证方式是 caching_sha2_password 也是通过密码登录的方式连接数据库
sql: create user 'root'@'%' identified by '123456';
# 给该用户赋权限
sql: grant all on *.* to 'root'@'%';
|
允许其他主机访问mysql
此时从其他机器是访问不了ubantu数据库的, 因为数据库默认的绑定地址是127.0.0.1 , 也就是说它只对本机的访问做了监听, 所以需要修改mysql的监听地址
1
2
3
4
5
6
|
$ vi etc/mysql/mysql.conf.d/mysqld.cnf
# 修改一下内容
bind-address = 127.0.0.1
# 改为
bind-address = 0.0.0.0
|
现在 可以通过其他主机的mysql访问ubantu的mysql了
1
2
|
$ mysql -h 192.168.21.123 -u root -p
Password:
|