Skip to content

Automatic login for MySQL

23/06/2011

Do you ever get tired from having to type a long line of code whenever you log into MySQL? Do you have scripts that access MySQL, but you hate having to store the MySQL password in the script itself?

The easiest solution to these sort of problems is to create a file in your home directory named .my.cnf. Give it the following contents:

# MySQL login file
[client]
user=root
password=reallysafepassword
database=somedatabase

The ‘database’ line is optional by the way, and you can use any user you want (using ‘root’ might not be a good idea in most cases, especially production environments. Once you have this in place, simply type ‘mysql’ and WHAMMO! You got yourself your MySQL prompt. If you use mysql in a script, you can leave out stuff like “-uroot -hlocalhost -p”. You also gain the advantage that you no longer have to remember passwords to your database, so you can harden your MySQL with a complicated password which is hard to crack (48 character random string for instance).

Do make sure your $HOME/.my.cnf file is set to chmod 600 (meaning – rw- — —) so other users won’t be able to read your password anymore. Don’t forget to do that, otherwise anyone with access to the .my.cnf file will be able to access your MySQL account as well.

Advertisement
Leave a Comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.