A Method of Fast Login to MySQL Database Without Password under Shell

  • 2021-08-12 03:52:55
  • OfStack

Background

When we want to log in to the MySQL database through mysql-client under Shell, we always need to enter the password again and again.

Moreover, if your root password is highly random (LastPass solution is good), then the cost of logging in to MySQL database once will be very high.

Usually when we log in to the database, we log in like this, as follows


root@imlonghao:~# mysql -uroot -p
Enter password: 

So, is there a way to log in to the database safely and easily?

Method

Of course, the answer is yes, and MySQL has already helped us think about this problem!

Reference link: End-User Guidelines for Password Security

Log in quickly using. my. cnf

Create a new. my. cnf file in the ~/directory. Of course, if you already have this file, you can modify it directly!

Personally, I like to use vim solution, so we can do this


vim ~/.my.cnf

Then write the following information to the file


[client]
password=your_pass
user=your_user

Note: Change your_pass and your_user to the password and username of the user you want to log in to

Here's an example:


[client]
password=mysqlrootpassword123321
user=root

If you already have the file. my. cnf, just write the information in the [client] field!

Note: Because your password is written in clear text in the. my. cnf file, you should pay attention to setting the file permissions of this file


root@imlonghao:~# chmod 400 ~/.my.cnf

After saving, we can directly use the mysql command to log in to the MySQL database!

Note: If you need to specify a setup file instead of using the default ~/. my. cnf, you need to use the --defaults-file=file_name Parameters. Example:


root@imlonghao:~# mysql --defaults-file=/home/imlonghao/mysql-opts

Quick login using the environment variable MYSQL_PWD

MySQL preferentially uses parameters in environment variables as operational parameters


root@imlonghao:~# export MYSQL_PWD=your_pass

After setting, you don't need to enter the password again when you log in to mysql again.

However, it should be noted that if you exit the current Shell, this environment variable will disappear.

More importantly, the commands you entered in Shell will be automatically saved, and history can see the commands you entered.

Summarize


Related articles: