mysqldump – How to Use in Cron Job Without Root Password

cronMySQLscripting

If I login with the root password on my box I can simply type

mysqldump –all-databases and I will get th expected "Dump".

I setup a job in cron.daily to run and dump this to a backup drive. The problem I have is that although the user is running as root I get the following message

mysqldump: Got error: 1045: Access denied for user 'root'@'localhost' (using password: NO)

when trying to connect. I do not want to hard code the mysql database root password in the script (who would).

Considering that I can just type "mysqldump" at the command line in my bash shell there must be someway to get around using the -u parameter.I already have #!/bin/bash at the top of the script.

What am I missing here to get this to not ask for the root password to the database?

Best Answer

In order to connect to the mysql server you must provide credentials. You can specify them in a configuration file, pass them via the command line, or simply create account that doesn't require credentials.

Of course the no-password option should never be used, the pass-by command line isn't great because anyone who can run ps may be able to see the command line.

The recommended option is to create a mysql configuration file with the credentials in it and then protect that file with filesystem permissions so only your backup user can access it.

You being able to login to the mysql server while logged in interactively as root seems to suggest that you either don't have a root password set, or that you have a configuration file that is not being found by your script. If you have a .my.cnf you may need to manually point to it. If your root account doesn't have a password set then I would strongly encourage you to fix that.

Update (2016-06-29) If you are running mysql 5.6.6 or greater, you should look at the mysql_config_editor tool that allows you to store credentials in an encrypted file. Thanks to Giovanni for mentioning this to me.