方法一:通過設置client標簽,直接編輯/etc/my.cnf文件
[client] user=root password=123456 port = 3306
我們直接輸入mysql就可以進行登錄mysql數據庫,這種不好的地方就是我們的密碼是不加密的,可見的,是不安全的。
[root@tz-ftp-yum ~]# mysql Welcome to the MySQL monitor. Commands end with ; or \g. Your MySQL connection id is 17 Server version: 5.7.25-log MySQL Community Server (GPL) 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. root@localhost [(none)]>
方法二:通過mysql_config_editor命令。
[root@tz-ftp-yum ~]# mysql_config_editor set -G vml -S /tmp/mysql.sock -u root -p Enter password: [root@tz-ftp-yum ~]#
我們配置完成之后就會在這個用戶目錄下面生成一個.mylogin.cnf的二進制文件
[root@tz-ftp-yum ~]# file /root/.mylogin.cnf
/root/.mylogin.cnf: data
我們print之后就可以發現,我們創建了一個標簽,標簽的名字就是vml,密碼是加密的,我們這樣就看不到密碼了,並且這種存儲方式是二進制的,相對比較安全
[root@tz-ftp-yum ~]# mysql_config_editor print --all [vml] user = root password = ***** socket = /tmp/mysql.sock
我們可以通過--login-path=vml這種方式進行免密碼登錄數據庫
[root@tz-ftp-yum ~]# mysql --login-path=vml Welcome to the MySQL monitor. Commands end with ; or \g. Your MySQL connection id is 20 Server version: 5.7.25-log MySQL Community Server (GPL) 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. root@localhost [(none)]>
方法三:我們通過my.cnf來配置,設置到~/.my.cnf來配置免密碼
[root@rsync-test03 ~]# cat .my.cnf [client] user=root password=123456 port = 3306
故障排查
再使用MySQL免密碼登錄的過程中,提示如下報錯
權限全局可寫,任何一個用戶都可以寫。mysql擔心這種文件被其他用戶惡意修改,所以忽略掉這個配置文件。這樣mysql無法重啟。
[root@rsync-test03 ~]# mysql mysql: [Warning] World-writable config file '/root/.my.cnf' is ignored. ERROR 1045 (28000): Access denied for user 'root'@'localhost' (using password: NO)
查看.my.cnf文件發現該文件的權限不對。重新授權
[root@rsync-test03 ~]# chmod 600 .my.cnf [root@rsync-test03 ~]# ll .my.cnf -rw------- 1 root root 47 Oct 31 19:06 .my.cnf
