从 MySQL 5.6 开始,提供了一个新的实用程序:mysql_config_editor,它允许你将身份认证信息存储到一个名为 .mylogin.cnf 的登录路径文件中,该文件的内容进行了混淆加密。对于 Windows 系统,该文件位于 %APPDATA%\MySQL 目录中;对于其他系统,该文件位于当前用户的家目录中。
配置了登录路径文件之后,MySQL 客户端程序连接服务器时可以使用其中的内容进行认证,不需要每次都输入登录信息。
先看没有进行设置之前的情况,我们使用 MySQL 8.0 版本,操作系统为 CentOS 7:
[root@mysql80 ~]# cat /etc/redhat-release
CentOS Linux release 7.4.1708 (Core)
[root@mysql80 ~]# mysql -uroot -p
Enter password:
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 11
Server version: 8.0.13 MySQL Community Server - GPL
Copyright (c) 2000, 2018, 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>
我们在使用 root 登录时,系统提示需要输入密码。接下来使用 mysql_config_editor 进行设置。
[root@mysql80 ~]# mysql_config_editor set --login-path=localroot --host=localhost --port=3306 --user=root --password
Enter password:
其中,set用于设置一个登录路径;--login-path用于指定登录路径名称,随后可以使用该名称进行登录;其他信息和直接登录时一样,执行该命令需要输入一次密码。
执行成功后,就会在当前用户的家目录(此处为 /root)中创建一个隐藏的文件,其中存储了我们设置的登录信息。
[root@mysql80 ~]# ls -l .mylogin.cnf
-rw-------. 1 root root 156 Dec 20 02:56 .mylogin.cnf
当我们再次登录时,就可以使用登录路径,而不需要输入密码了:
[root@mysql80 ~]# mysql --login-path=localroot
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 12
Server version: 8.0.13 MySQL Community Server - GPL
Copyright (c) 2000, 2018, 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>
就是这么简单。以下为官方文档内容,仅供参考:
文件 .mylogin.cnf 未加密之前的内容和其他的选项文件类似,也是由多个选项组构成。每个选项组称为一个“登录路径”,其中只能包含以下特定的选项信息:host、user、password、port 以及 socket。每个选项组就是一系列连接选项,指定了要连接的 MySQL 服务器和账户信息。以下是一个未加密之前的登录文件示例: