In this post, we will learn how to avoid passing the password for the shell script manually.
You can either:
- Put the password in the [client] or [mysql] section of a .my.cnf file in your home directory.
- Use an authentication mechanism (e.g. PAM) that does not rely on passwords
- Make the password as dynamic variable and pass it in the crontab as an argument (however, this is less secure way of doing it)
For the third case, here is an example:
In the script:
"mysql -u root -p$PASS mysql << [...other options...]
And in the crontab:
0 0 * * * bash /path/to/script/file.sh secretpwd [...other options...]
From MySQL 5.6.6 onwards, you could use an encrypted login file.
Example to use the mysql_config_editor utility
1. Setup a login-path, any name can be used to set login-path and pass the user credentials you wanted to use for mysqldump.
$ path/to/5.6.13/bin/mysql_config_editor set --login-path=dump --host=localhost --user=root --password --socket=/tmp/mysql_5613.sock Enter password:
2. Once you enter the password, it will create a encrypted entry in the file ~/.mylogin.cnf , it is not necessary you should pass the user as root, you could use any user you have for the backup purpose.
3. Confirm if the config editor has created this info by running the below command:
$ path/to/5.6.13/bin/mysql_config_editor print --all [dump] user = root password = ***** host = localhost socket = /tmp/mysql_5611.sock
Now you are all set to execute the mysqldump without passing any password, ensure you pass the login-path name correctly, so the connection details will be fetched from the encrypted file.
$ path/to/5.6.13/bin/mysqldump --login-path=dump --all-databases > test_backup.sql
Use a hidden file for storing the password
Save the password in a hidden file and while scheduling in crontab, awk the position of the password as a script argument.