MySQL 버전이 점점 올라가면서 언제부터인가 mysql 명령어로 접속시 비밀번호를 같이 입력하면 아래와 같이 안전하지 않다는 경고가 나온다.
$ mysql -hlocalhost -udb_user -pdb_password
mysql: [Warning] Using a password on the command line interface can be insecure.
쉘 스크립트로 DB 접속하는 작업을 하는 경우 위와 같이 명령어에 비밀번호까지 같이 입력하는 경우가 많은데 실행은 되지만 경고가 나오는게 매우 거슬린다.
이런 경우는 아래 2가지 방법으로 해결이 가능하다.
방법1)
계정 home path (리눅스 기준 /home/userid 등) 에 .my.cnf 파일을 생성하고 아래와 같이 내용을 입력한다.
[client]
host=localhost
user=db_user
password=db_password
생성한 후에 mysql 명령만 실행하면 바로 접속이 가능하다.
$ mysql
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 47904
Server version: 8.0.23 Source distribution
Copyright (c) 2000, 2023, Oracle and/or its affiliates.
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>
이렇게 하면 간편하게 접속을 할 수 있으나, 지정된 DB 한곳만 접속이 가능하고, 다른 DB (host 기준) 에 접속하려면 기존처럼 mysql 에 -h 옵션을 사용해서 접속을 해야 한다.
DB를 여러개 사용하는 경우 아래 방법으로 사용하면 된다.
방법2)
mysql_config_editor 명령을 사용하여 DB 별로 profile 을 생성한다.
$ mysql_config_editor set --login-path=dev --host=localhost --user=root --password
위와 같이 실행하면 비밀번호 입력 프롬프트가 나오고, 비밀번호를 입력하면 완료된다.
계정 home path 에 보면 .mylogin.cnf 파일이 생성되어 있을것이다. (바이너리 형식이라 내용은 보기 어려움)
--login-path 의 값을 다르게 하여 여러 DB 정보를 등록해 두고, mysql 접속시 아래와 같이 접속한다.
$ mysql --login-path=dev
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 9759
Server version: 8.0.23 Source distribution
Copyright (c) 2000, 2023, Oracle and/or its affiliates.
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>
등록된 정보 확인
$ mysql_config_editor print --all
[dev]
user = "user1"
password = *****
host = "host1"
[stg]
user = "user2"
password = *****
host = "host2"
[prod]
user = "user3"
password = *****
host = "host3"
등록된 정보 삭제
mysql_config_editor remove --login-path=dev
등록된 비밀번호는 암호회 되어서 .mylogin.cnf 에 저장되어 바로 확인은 어렵지만, 아래 명령어를 통해 비밀번호 확인이 가능하다.
$ my_print_defaults --show dev
--user=user1
--password=password1
--host=host1