目錄表

[*nix] Handle mysql password in command line warning

0x00 前言

我在寫 shell script 時需要連接到資料庫,而連接時需要密碼

若直接使用--password 參數和密碼,mysql 會跳出警告

Warning: Using a password on the command line interface can be insecure.

且使用 htopps 指令都會看到程式執行參數和密碼

後來找到 mysql 官方解法,記錄於此


0x01 How To

根據官方描述,在 mysql 5.6.6 版之後,有個叫做 mysql_config_editor 的工具

使用方式如下

在 command 先下

mysql_config_editor set --login-path=mypath --host=myhost --user=username --password

接著輸入密碼

之後 mysql_config_editor 會在使用者家目錄下產生 .mylogin.cnf 檔案,權限必須為 600 (預設),只有該使用者能讀寫,否則 mysql 不會使用此設定檔

.mylogin.cnf 是加密過的,若要讀取內容可以使用

mysql_config_editor print --all

輸出格式大約如下,每個 [] 表示一個 path,可設定多組 path

[mypath]
user = myothername
password = *****
host = localhost
[remote]
user = user
password = *****
host = remote.xyz

接著在 shell script 中使用 –login-path 指定要用的 path

mysql --login-path=mypath 

取代

mysql --user=user --host=host.xyz --password=mypasswd

就順利處理掉密碼安全性問題啦

這邊要注意 –login-path 一定要放在 mysql的第一個參數,否則會出現 unknown parameter error

另外自己測試發現 sudo 無法搭配 mysql_config_editor,他還是會用原來使用者身分去建 .mylogin.cnf
原因暫無深究,如果需要 root 使用就直接用 su 吧

若要移除一筆資料可使用

mysql_config_editor remove --login-path=mypath

0x02參考資料