Using mysqldump in cron job without root password

Solution 1:

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.

Solution 2:

Security should not be done through obscurity. If you afraid that someone has access to your root account, it doesn't matter if root's mysql password is stored in the script, since you have all your data available in mysql dumps, or database files. So, the real question is what are you trying to protect?

If you don't want others to get a password that will let them change data in your database, you would need to create a user with appropriate permissions.

If you don't want that mysql password to be seen by any local account except root set file permissions on that script to be 0700 and owner to root.


Solution 3:

Your shell use can do it becuase you have a shell to run it from, ie when you logon, all your shell scripts in your profile get run.

Cron does not have such luxuries. When it logs on (as root) it'll log on with a default shell. This prevents anyone from logging on remotely, but it also means there is no auto-login scripts that are run.

You can set a shell for cron to run under, edit the crontab and add the SHELL and HOME variables, eg.

SHELL=/bin/bash
HOME=/root

if these are not set, then cron will run with the shell and home directory specified in /etc/passwd (which are probably nothing, possibly /bin/sh).

If you want to see the environment cron is running as, add a cron job that exports env to a file, eg:

$crontab -e
* * * * * env > /tmp/crontabenv.log
:wq