Do you work with MySQL? I do… quite a bit.
Do you often script stuff on your server to make your life easier? I do that as well… quite a bit…
Are you including your database user account and password (or worse… your mysql instance root user account and password!) in plain-text in your script… I was doing this… and it is bad practice from a security standpoint for sure…
Okay, so if you have a bunch of scripts (and I have several for database maintenance and database backups) floating around and many of them contain your MySQL root user account credentials… that can be a real issue. There is a better way!
This method still involves storing your password in plain-text. However, we are going to be storing it in a file that is only accessible by root and we are only going to be storing it in one place.
Login to your server, elevate to root, then go to the home directory for root.
From here, we are going to create a file called .my.cnf and drop our account info into it. So… like so…
That opens up a new file using the VIM text editor. Inside of here you need to put your information in based on my example here:
user = root
password = '[email protected]'
host = localhost
Save and close. Finally, set permissions on that file so that only root has full access to it…
Finally you can test by simply typing “mysql” and hitting enter. If you aren’t told to get out of dodge because you didn’t supply a password then your file is working just fine.
Here is the added bonus, and the point of this article, any scripts that are executed by root can now just use the mysql or mysqladmin command and there is no need to specify your credentials in the script.
The only downside to this method I can figure is that if your server’s root account is compromised there is just one less layer a devious person has to penetrate to get to your data. That being said, you probably aren’t encrypting your database anyway right? So if your root account is compromised it is pretty much game over. I also appreciate only having to worry about one file on my system vs. several that are floating around with credentials in them.