How to securely login to MySQL without providing password each time?

How to securely login to MySQL without providing password each time?

's avatar
Bobby Iliev ・June 29, 2020
1 minute read ・Updated July 17, 2020

Introduction

Using a long and secure MySQL password is necessary, however having to type that long password every time you run mysql -u root -p could be a bit frustrating especially if you want to run some MySQL commands in a script without being prompted for a password.

One way to login to MySQL is to append your password right after the -p flag:

mysql -u root -pYOUR_PASSWORD`

However, using a password on the command line interface can be insecure. This will also be recorded in your bash history.

Here is a better and more secure way on how to do that!

Prerequisites

In order to be able to follow along, you will need a Linux server with MySQL installed.

I will be using an Ubuntu Droplet deployed on DigitalOcean. If you wish to follow along you can sign up for DigitalOcean via my referral link below and you will get $100 free DigitalOcean credit:

[https://m.do.co/c/2a9bba940f39](Free $100 DigitalOcean Credit)

Configuration of .my.cnf

By configuring the ~/.my.cnf file in your user's home directory, MySQL would allow you to login without prompting you for a password.

In order to make that change, what you need to do is first create a .my.cnf file in your user's home directory:

Checkout our latest product - the ultimate tailwindcss page creator πŸš€
touch ~/.my.cnf

After that set secure permissions, so that other regular users could not read the file:

chmod 600 ~/.my.cnf

Then using your favorite text editor open the file:

nano ~/.my.cnf

And add the following configuration

[client]
user=YOUR_MYSQL_USERNAME
password=YOUR_MYSQL_PASSWORD

Make sure to update your MySQL credentials accordingly, then save the file and exit.

After that, if you run just mysql you will be authenticated directly with the credentials that you've specified in the ~/.my.cnf file without being prompted for a password.

Testing with mysqladmin

As a quick test you could check all of your open SQL connections by running the following command:

mysqladmin proc

The mysqladmin tool would also use the client details from the ~/.my.cnf file and it would list your current MySQL process list.

Another cool thing that you could try doing is combining this with the watch command and kind of monitor your MySQL connections in almost real-time:

watch -n1 mysqladmin proc

To stop the watch command just hit CTRL+C

Conclusion

Adding your MySQL client details in your ~/.my.cnf could be a good way to speed up your workflow and access your MySQL server without typing your password each time.

This is also super handy in case you want to run some MySQL commands via a bash script.

Hope that this helps!

Bobby

Comments (0)