auto authenticate password in mysql - mysql

I am new to MySql. In postgres, we can use .pgpass and save user password so that the database can automatically authenticate your password whenever you access or execute your sql script. I don't have to enter password.
So is there any way to do the same thing for mysql on linux?
Thanks

Yes, you can store default credentials and other options in your home directory, in a file called $HOME/.my.cnf
$ cat > $HOME/.my.cnf
[client]
user = scott
password = tiger
host = mydbserver
^D
In MySQL 5.6, you can also store an encrypted version of this file in $HOME/.mylogin.cnf, see http://dev.mysql.com/doc/refman/5.6/en/mysql-config-editor.html
$ mysql_config_editor set --user=scott --host=mydbserver --password
Enter password: ********
WARNING : 'client' path already exists and will be overwritten.
Continue? (Press y|Y for Yes, any other key for No) : y
$ mysql_config_editor print --all
[client]
user = scott
password = *****
host = mydbserver

You could use the command-line parameters available to the MySQL executable within a quick Bash script to accomplish this. See http://dev.mysql.com/doc/refman/5.6/en/mysql.html for
the details. Basically, the following line would log you into MySQL
$>mysql --user=root --password=toor my_database
The command above would log you into the mysql database "my_database" as root using the password "toor"
Now but this into a quick Bash script (run_mysql.sh):
#!/bin/bash
/usr/bin/mysql --user=root --password=toor my_database
Make sure the script is executable:
chmod +x ./run_mysql.sh
Of course make sure this script is safely stored somewhere other users cannot access it such as your home folder and set the permissions accordingly.

Related

How can I execute remote MySQL queries via shell script without putting open text password in my shell script?

I'd rather not execute a query in a shell script with an open text password.
#!/bin/bash
mysql -uuser -hremotehost -pmypassword -e "update my_table set what_time = NOW()";
Is there a way to put mypassword in my local /etc/my.cnf file or something else to keep it out of open text command line?
Assume my remotehost doesn't accept no password for mysql.
As written over at dba it is possible to configure your my.cnf file as the following:
[clienthost1] # Note: client + host1
user=user
password=mypassword
host=remotehost
and run it as:
mysql --defaults-group-suffix=host1
Kudus to Derek Downey answer at DBA
Another option is to use mysql_config_editor and store the data in an encrypted file.
Example:
mysql_config_editor set --user=user --password --host=remotehost
Enter password:
UPDATED ANSWER
Create ~/.my.cnf file and put the following into it:
[foo]
user=user
password=mypassword
host=remotehost
[bar]
user=user2
password=some-other-password
host=127.0.0.1
Then invoke mysql --login-path=foo ... to connect to remotehost or mysql --login-path=bar ... for local host.

mysqldump Error 1045 Access denied despite correct passwords etc

This is a tricky one, I have the following output:
mysqldump: Got error: 1045: Access denied for user 'root'#'localhost' (using password: YES) when trying to connect
When attempting to export my database with mysqldump on Windows XP. The username is root, the password is correct and contains only alphanumeric characters. I have tried different cases, with/without quotes, specifying using -u and -p, specifying using --user= and --password= and other methods of specifying user/passwords etc, specifying the host (it's all local) and even specifying the database using --databases instead of just blank. The error is always the same when using a password and always the same except the "NO" message when without. I have tried many fixes found through searches with no success. One fix suggested inspecting mysql.conf, but the Windows build doesn't seem to have one. The credentials (and indeed commandline parameters) work perfectly with mysql.exe - this problem only seems to be affecting mysqldump.exe.
This worked for me
mysqldump -u root -p mydbscheme > mydbscheme_dump.sql
after issuing the command it asks for a password:
Enter password:
entering the password will make the dump file.
If you're able to connect to the database using mysql, but you get an error for mysqldump, then the problem may be that you lack privileges to lock the table.
Try the --single-transaction option in that case.
mysqldump -h database.example.com -u mydbuser -p mydatabase --single-transaction > /home/mylinuxuser/mydatabase.sql
Try to remove the space when using the -p-option. This works for my OSX and Linux mysqldump:
mysqldump -u user -ppassword ...
The access being denied is probably to the Windows file system not to the MySQL database; try redirecting the output file to a location where your account is allowed to create files.
You need to put backslashes in your password that contain shell metacharacters, such as !#'"`&;
Don't enter the password with command. Just enter,
mysqldump -u <username> -p <db_name> > <backup_file>.sql
Then you will get a prompt to enter password.
Access dined problem solved when I run command prompt in Administrator mode.
Go to Start-> All Programs -> Accessories right click on Command Prompt clickc on Run as.. Select The Following User select administrator username from select option enter password if any click OK button.
Example 1: For entire database backup in mysql using command prompt.
In Windows 7 and 8
C:\Program Files <x86>>\MySQL\MySQL Server 5.5\bin>mysqldump test -u root -p >testDB.sql
Enter Password: *********
In Windows xp
C:\Program Files\MySQL\MySQL Server 5.5\bin>mysqldump test -u root -p >testDB.sql
Enter Password: *********
It asks password for credentials enter password and click on Enter button.
Example 2: For specific table backup / dump in mysql using command prompt.
In Windows 7 and 8
C:\Program Files <x86>>\MySQL\MySQL Server 5.5\bin>mysqldump test -u root -p images>testDB_Images.sql
Enter Password: *********
In Windows xp
C:\Program Files\MySQL\MySQL Server 5.5\bin>mysqldump test -u root -p images>testDB_Images.sql
Enter Password: *********
Dumpt file will be created under folder
In windows xp
C:\Program Files\MySQL\MySQL Server 5.5\bin
In windows 7 and 8
C:\Program Files (x86)\MySQL\MySQL Server 5.5\bin
Note: Check MySQL installation folder in Windows 7, 8 while run in command prompt. If MySQLWorkbench is 32 bit version it is installed in Program Files (x86) folder other wise Program Files folder.
Put The GRANT privileges:
GRANT ALL PRIVILEGES ON mydb.* TO 'username'#'%' IDENTIFIED BY 'password';
mysqldump -h hostname -u username -P port -B database --no-create-info -p > output.sql
I think you should specify the args
Doing without the -u and -p worked for me (when I was logged in as root):
mysqldump --opt mydbname > mydbname.sql
I was having the same issue, for 30min! I found that I was using _p instead of -p, the terminal font confused me!
Putting -p as the first option worked for me on Windows Server 2012R2 (in cmd.exe as Admin).
mysqldump.exe –p --user=root --databases DBname --result-file=C:\DBname.sql
I just ran into this after a fresh install of MySQL 5.6.16.
Oddly, it works without the password specified or flagged:
mysqldump -u root myschema mytable > dump.sql
mysqldump -u (user) -p(passwd) -h (host_or_IP) database_to_backup > backup_file.sql
example:
mysqldump -u god -pheaven -h 10.0.10.10 accounting > accounting_20141209.sql
this would create sql backup file for the accounting database on server 10.0.10.10. Sometimes your error is seen when localhost is not in config. Designating ip of server may help.
I had to remove the single ticks after the password flag:
--password=mypassword
and NOT
--password='mypassword'
Mysql replies with Access Denied with correct credentials when the mysql account has REQUIRE SSL on
The ssl_ca file (at a minimum) had to be provided in the connection paramiters.
Additional ssl parameters might be required and are documented here: http://dev.mysql.com/doc/refman/5.7/en/secure-connection-options.html
Also posted here https://stackoverflow.com/a/39626932/1695680
For MAMP PRO users (or anyone who's mysql is in a weird location) be prepared to specify the mysql full path from the boonies and also specify full path to your user local folder where you want to dump the file or you'll get the "permission denied error"..
Following worked for me after 3 hours of research:
/Applications/MAMP/Library/bin/mysqldump -u root -proot YOUR_DB > /Users/YOUR_USER/yourdump2.sql
In my case, I could access correctly with mysql.exe but not with mysqldump.exe.
The problem was the port for my connection was not the default one (3306) and I had to put the mysqldump port work with (-P3307)
mysqldump -u root -p -P3307 my_database > /path/backup_database
This is the solution that worked for me
mysqldump -h hostname.com -u username -p'password' database > dump.sql
In Past same problem occurred to me after I copied the mysqldump statement from a MS Word file.
But When typing the statement directly, everything worked fine.
In hex editor the "-" of the not working statement was represented by the unicode char e2 80 93 (http://www.fileformat.info/info/unicode/char/2013/index.htm)
In sort, type password directly and check the copy paste code as the uni-code (or other encoding) strings might cause an issue..
I had the same error for last 2 days. Tried bunch of things. Nothing worked.
But this did work:
Create another user. Grant it everything.
mysqldump -u new_user db_name > db_name.sql //no error
I discovered a running apache process acessing the MYSQL causing this error. So I suggest to ensure that all processes which might interact with the DB are shutdown beforehand.
I had the problem that there were views that had a bad "DEFINER", which is the user that defined the view. The DEFINER used in the view had been removed some time ago as being "root from some random workstation".
Check whether there might be a problem by running:
USE information_schema;
SELECT DEFINER, SECURITY_TYPE FROM views;
I modified the DEFINER (actually, set the DEFINER to root#localhost and the SQL SECURITY value to INVOKER so the view is executed with the permissions of the invoking user instead of the defining user, which actually makes more sense) using ALTER VIEW.
This is tricky as you have to construct the appropriate ALTER VIEW statement from information_schema.views, so check:
Modify DEFINER on many
views
MySQL error 1449: The user specified as a definer does not exist
For me it worked when I omitted the password.
So mysqldump -u user dbname > dump.sql
Tried most of the above with no joy.
Looking at my password, it had characters that might confuse a parser. I wrapped the password in quotes and the error was resolved.
-p"a:##$%^&+6>&FAEH"
Using 8.0
If you want to create a mysql data dump, you can use mysqldump command. Following command will create a sql file called xxx.sql at the same location from where this command is run. xxx.sql will have all the necessary sqls to replicate exactly same db schema in any other mysql database.
Command is : mysqldump -u root -ppassword --databases database Name you want to import > xxx.sql
Here root is the mysql root user and password is THIS root user's password.
EXAMPLE: If root user password is hello, database name to export is regdb and xxx.sql is the file where you want to export this regdb, command would be like:
mysqldump -u root -phello --databases regdb > xxx.sql
Note: xxx.sql is the file name where this db will get dumped.
This solution might be one of the last to try/least likely to be the culprit, but this was my problem...
My problem was that the directory I was trying to dump to needed admin privileges to write to and that's what was causing the mysqldump command to return "Access Denied".
I set the dump file path to my desktop dir and then it worked.
This was on Windows.
I had the same error. Only occurred after moving from my normal work PC to a PC at a different location.
I had to add my public IP ho address to Remote MySQL in my CPanel at my host site
I got the same error when I ran the command in a directory that I didn't have write access to.
Test your access by creating an empty file in the directory, and see if you get an error.
Here was my error
mysqldump -u root librenms -p > librenms.sql
-bash: librenms.sql: Permission denied
I changed to my home directory and then it worked.
cd ~
mysqldump -u root librenms -p > librenms.sql
Enter password:
Do the equivalent on windows, and it may just fix your problem!
ENSURE YOU TRY REMOVING AND TYPING THE DASH OVER to make sure that you are actually fighting with the right problem.
Be very careful that you actually have a "-". I apparently had some other character that looks very similar. I had a – instead of a -. I had copied the command from somewhere online don't remember where but the point is I spend a lot of time trying to figure it out when I just needed to replace that character.

Setting mysql as shell

I have a user on my machine that is only supposed to run mysql. Is there any way that I can set the shell of that user to mysql and login using password and username?
I know how to change the shell to the mysql binary
usermod -s /usr/bin/mysql
That is working indeed, only I can't provide a username/password in the program. Usually user/pw are given as
mysql -u $USER -p
I can not provide parameters for a shell as in
usermod -s "/usr/bin/mysql -u $USER -p" # Does not work!
Also using a simple shell-script as shell does not work:
#!/bin/sh # mysqlShell
/usr/bin/mysql -u $USER -p
----
usermod -s mysqlShell # does not work
So how can I provide parameters to a program I use as a shell for a user?
Thanks to Tom Regner I could figure out a solution using .my.cnf containing
[client]
host=localhost
user=$user
password=$pass
disable-auto-rehash
where mysql is set to the shell. I still would like give the password manually but this is the best I found.
Setup a $HOME/.my.cnf file for the user
[client]
host=localhost
user=mysqluser
password=mysqlpass
then set a bash as login shell and put the following in $HOME/.bashrc
exec mysql --host=localhost dbname
that should do what you want, while the user in question just has to give one password (the system account password on login).
exec replaces the shell process with the mysql process.
If this does not work as expected, you may need to adjust $HOME/.bash_profile to source .bashrc:
[[ -f ~/.bashrc ]] && . ~/.bashrc
It might be enough to provide an appropriate .my.cnf and setting /usr/bin/mysql as shell, but this way you can pass arbitrary commandline options/flags to the mysql client.
You can do that by editing the user's account details in the /etc/passwd and change the default shell.
You need a login password (unless you set up ssh appropriately). Use the following command: sudo passwd username to change that login password.
You also need a mysql password. Use SET PASSWORD Mysql request.
If you want the user to be connected to some fixed database with some fixed password, code a small C wrapper (then, make the executable only executable by your Unix user) doing mysql_real_connect, or calling some exec function for mysql --user=username --password=password databasename but I don't recommend doiing the later (because ps aux will show the password, and that is a security risk).
Perhaps, since MySQL is free software, you could customize the source code of mysql for your particular needs.
Perhaps using a restricted shell and carefully configuring it is better.

How to enter password in mysql5.5 using batch script?

i have written a batch script but it still ask me for a password. i want to enter it automatically. please help me
here is my batch script :
setlocal EnableDelayedExpansion
c:
cd "C:\Program Files\MySQL\MySQL Server 5.5\bin"
mysql -u root -p root
but still in output it ask for a password as:
Enter Password :
i got the answer. for that find below my comment
You can't have a space between the option and the password. So it should be:
mysql -u root -proot
Or use --password=root
For other googlers like me, I'll add my solution.
Unfortunately, official documentation doesn't tell this clearly
Short parameters like these didn't work to me and prompted for password
mysqldump -uroot -p "qwerty" mybase > Z:\mybase.sql
With "full" name parameters it worked, just warning about this action as insecure
mysqldump --user="root" --password="qwerty" mybase > Z:\mybase.sql
echo 'Backup OK' > mysql_dump.log
Problem Solved Got the solution
c:
cd "C:\Program Files\MySQL\MySQL Server 5.5\bin"
mysql -uroot -proot -e "delete from db.tablename where columnname =
'something';
The problem is In this line "setlocal EnableDelayedExpansion"
This should be deleted. and the code runs smoothly :)
AFAIK you cannot do this using the mysql bin, but mysqladmin can.
See the docs here: http://dev.mysql.com/doc/refman/5.5/en/mysqladmin.html
-ppassword displays warning
Warning: Using a password on the command line interface can be insecure.
https://dev.mysql.com/doc/refman/5.7/en/password-security-user.html
Solution: You can use cnf options file
https://dev.mysql.com/doc/refman/5.7/en/option-files.html
linux:
echo -e "[client]\nhost=mysqlhost\nport=3306\nuser=root\npassword=${ROOT_PASS}" > root.cnf
mysql --defauls-file=root.cnf -e "SELECT * FROM users;" ${MYDB}
windows:
Ship root.cnf file with batch script and run
"C:\Program Files\MySQL\MySQL Server 5.5\bin\mysql" --defauls-file=root.cnf -e "SELECT * FROM users;" %MYDB%
try this create a file for password .pw and below command works in batch fine.
mysql --default-file=C:\path*.pw -u %username% blah blah..
Your best option is to use MySQL options files.
MySQL 5.5 makes use of the .my.cnf file, you just need to supply your username and password. This approach means you can login to mysql just by typing mysql in your script and the .my.cnf file will fill in the rest; Here's how:
Create a .my.cnf file in the home directory of the user which will run the script. The contents should look like the following code block, swapping out your_user and your_password for their actual values.
[client]
user=your_user
password=your_password
It's prudent to change the permission of this file to either 400 or 600, this will mean only your user and root will be able to see the file.
chmod 600 .my.cnf
You're all set!
N.B.
From version 5.6 onwards you can use the mysql_config_editor utility, which generates a .mylogin.cnf, it has the same result as the above apporoach with the added benefit that the password will be encrypted by the utility.
Links
MySQL 5.5
https://dev.mysql.com/doc/refman/5.5/en/password-security-user.html
MySQL 5.6+
https://dev.mysql.com/doc/refman/8.0/en/mysql-config-editor.html
This worked for me, put it in a .bat file, and change the password with yours.
#echo OFF
setlocal EnableDelayedExpansion
C:
cd "C:\xampp\mysql\bin\"
mysql.exe --user="root" --password="the password"

How to perform a mysqldump without a password prompt?

I would like to know the command to perform a mysqldump of a database without the prompt for the password.
REASON:
I would like to run a cron job, which takes a mysqldump of the database once everyday. Therefore, I won't be able to insert the password when prompted.
How could I solve this ?
Since you are using Ubuntu, all you need to do is just to add a file in your home directory and it will disable the mysqldump password prompting. This is done by creating the file ~/.my.cnf (permissions need to be 600).
Add this to the .my.cnf file
[mysqldump]
user=mysqluser
password=secret
This lets you connect as a MySQL user who requires a password without having to actually enter the password. You don't even need the -p or --password.
Very handy for scripting mysql & mysqldump commands.
The steps to achieve this can be found in this link.
Alternatively, you could use the following command:
mysqldump -u [user name] -p[password] [database name] > [dump file]
but be aware that it is inherently insecure, as the entire command (including password) can be viewed by any other user on the system while the dump is running, with a simple ps ax command.
Adding to #Frankline's answer:
The -p option must be excluded from the command in order to use the password in the config file.
Correct:
mysqldump –u my_username my_db > my_db.sql
Wrong:
mysqldump –u my_username -p my_db > my_db.sql
.my.cnf can omit the username.
[mysqldump]
password=my_password
If your .my.cnf file is not in a default location and mysqldump doesn't see it, specify it using --defaults-file.
mysqldump --defaults-file=/path-to-file/.my.cnf –u my_username my_db > my_db.sql
A few answers mention putting the password in a configuration file.
Alternatively, from your script you can export MYSQL_PWD=yourverysecretpassword.
The upside of this method over using a configuration file is that you do not need a separate configuration file to keep in sync with your script. You only have the script to maintain.
There is no downside to this method.
The password is not visible to other users on the system (it would be visible if it is on the command line). The environment variables are only visible to the user running the mysql command, and root.
The password will also be visible to anyone who can read the script itself, so make sure the script itself is protected. This is in no way different than protecting a configuration file. You can still source the password from a separate file if you want to have the script publicly readable (export MYSQL_PWD=$(cat /root/mysql_password) for example). It is still easier to export a variable than to build a configuration file.
E.g.,
$ export MYSQL_PWD=$(>&2 read -s -p "Input password (will not echo): "; echo "$REPLY")
$ mysqldump -u root mysql | head
-- MySQL dump 10.13 Distrib 5.6.23, for Linux (x86_64)
--
-- Host: localhost Database: mysql
-- ------------------------------------------------------
-- Server version 5.6.23
/*!40101 SET #OLD_CHARACTER_SET_CLIENT=##CHARACTER_SET_CLIENT */;
/*!40101 SET #OLD_CHARACTER_SET_RESULTS=##CHARACTER_SET_RESULTS */;
/*!40101 SET #OLD_COLLATION_CONNECTION=##COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8 */;
MariaDB
MariaDB documents the use of MYSQL_PWD as:
Default password when connecting to mysqld. It is strongly recommended to use a more secure method of sending the password to the server.
The page has no mentions of what a "more secure" method may be.
MySQL
This method is still supported in the latest documented version of MySQL: https://dev.mysql.com/doc/refman/8.0/en/environment-variables.html though it comes with the following warning:
Use of MYSQL_PWD to specify a MySQL password must be considered extremely insecure and should not be used. Some versions of ps include an option to display the environment of running processes. On some systems, if you set MYSQL_PWD, your password is exposed to any other user who runs ps. Even on systems without such a version of ps, it is unwise to assume that there are no other methods by which users can examine process environments.
The security of environment variables is covered in much details at https://security.stackexchange.com/a/14009/10002 and this answer also addresses the concerns mentioned in the comments. TL;DR Irrelevant for over a decade.
Having said that, the MySQL documentation also warns:
MYSQL_PWD is deprecated as of MySQL 8.0; expect it to be removed in a future version of MySQL.
To which I'll leave you with maxschlepzig's comment from below:
funny though how Oracle doesn't deprecate passing the password on the command line which in fact is extremely insecure
Final thoughts
Connecting to a system using a single factor of authentication (password) is indeed insecure. If you are worried about security, you should consider adding mutual TLS on top of the regular connection so both the server and the client are properly identified as being authorized.
To use a file that is anywhere inside of OS, use --defaults-extra-file eg:
mysqldump --defaults-extra-file=/path/.sqlpwd [database] > [desiredoutput].sql
Note: .sqlpwd is just an example filename. You can use whatever you desire.
Note: MySQL will automatically check for ~/.my.cnf which can be used instead of --defaults-extra-file
If your using CRON like me, try this!
mysqldump --defaults-extra-file=/path/.sqlpwd [database] > "$(date '+%F').sql"
Required Permission and Recommended Ownership
sudo chmod 600 /path/.sqlpwd && sudo chown $USER:nogroup /path/.sqlpwd
.sqlpwd contents:
[mysqldump]
user=username
password=password
Other examples to pass in .cnf or .sqlpwd
[mysql]
user=username
password=password
[mysqldiff]
user=username
password=password
[client]
user=username
password=password
If you wanted to log into a database automatically, you would need the [mysql] entry for instance.
You could now make an alias that auto connects you to DB
alias whateveryouwant="mysql --defaults-extra-file=/path/.sqlpwd [database]"
You can also only put the password inside .sqlpwd and pass the username via the script/cli. I'm not sure if this would improve security or not, that would be a different question all-together.
For completeness sake I will state you can do the following, but is extremely insecure and should never be used in a production environment:
mysqldump -u [user_name] -p[password] [database] > [desiredoutput].sql
Note: There is NO SPACE between -p and the password.
Eg -pPassWord is correct while -p Password is incorrect.
Yeah it is very easy .... just in one magical command line no more
mysqldump --user='myusername' --password='mypassword' -h MyUrlOrIPAddress databasename > myfile.sql
and done :)
For me, using MariaDB I had to do this: Add the file ~/.my.cnf and change permissions by doing chmod 600 ~/.my.cnf. Then add your credentials to the file. The magic piece I was missing was that the password needs to be under the client block (ref: docs), like so:
[client]
password = "my_password"
[mysqldump]
user = root
host = localhost
If you happen to come here looking for how to do a mysqldump with MariaDB. Place the password under a [client] block, and then the user under a [mysqldump] block.
You can achieve this in 4 easy steps
create directory to store script and DB_backups
create ~/.my.cnf
create a ~/.script.sh shell script to run the mysqldump
Add a cronjob to run the mysql dump.
Below are the detailed steps
Step 1
create a directory on your home directory using sudo mkdir ~/backup
Step 2
In your home directory run sudo nano ~/.my.cnf and add the text below and save
[mysqldump]
#use this if your password has special characters (!##$%^&..etc) in it
password="YourPasswordWithSpecialCharactersInIt"
#use this if it has no special characters
password=myPassword
Step 3
cd into ~/backup and create another file script.sh
add the following text to it
SQLFILE=/path/to/where/you/want/to/dump/dbname.sql
DATABASE=dbname
USER=myUsername
mysqldump --defaults-file=~/.my.cnf -u ${USER} ${DATABASE}|gzip > dbName_$(date +\%Y\%m\%d_\%H\%M).sql.gz
Step 4
In your console, type crontab -e to open up the cron file where the auto-backup job will be executed from
add the text below to the bottom of the file
0 0 * * * ./backup/script.sh
The text added to the bottom of the cron file assumes that your back up shall run daily at midnight.
That's all you need folk
;)
Here is a solution for Docker in a script /bin/sh :
docker exec [MYSQL_CONTAINER_NAME] sh -c 'exec echo "[client]" > /root/mysql-credentials.cnf'
docker exec [MYSQL_CONTAINER_NAME] sh -c 'exec echo "user=root" >> /root/mysql-credentials.cnf'
docker exec [MYSQL_CONTAINER_NAME] sh -c 'exec echo "password=$MYSQL_ROOT_PASSWORD" >> /root/mysql-credentials.cnf'
docker exec [MYSQL_CONTAINER_NAME] sh -c 'exec mysqldump --defaults-extra-file=/root/mysql-credentials.cnf --all-databases'
Replace [MYSQL_CONTAINER_NAME] and be sure that the environment variable MYSQL_ROOT_PASSWORD is set in your container.
Hope it will help you like it could help me !
Check your password!
Took me a while to notice that I was not using the correct user name and password in ~/.my.cnf
Check the user/pass basics before adding in extra options to crontab backup entries
If specifying --defaults-extra-file in mysqldump then this has to be the first option
A cron job works fine with .my.cnf in the home folder so there is no need to specify --defaults-extra-file
If using mysqlpump (not mysqldump) amend .my.cnf accordingly
The ~/.my.cnf needs permissions set so only the owner has read/write access with:
chmod 600 ~/.my.cnf
Here is an example .my.cnf:
[mysql]
host = localhost
port = 3306
user = BACKUP_USER
password = CORRECTBATTERYHORSESTAPLE
[mysqldump]
host = localhost
port = 3306
user = BACKUP_USER
password = CORRECTBATTERYHORSESTAPLE
[mysqlpump]
host = localhost
port = 3306
user = BACKUP_USER
password = CORRECTBATTERYHORSESTAPLE
The host and port entries are not required for localhost
If your user name in linux is the same name as used for your backup purposes then user is not required
Another tip, whilst you are doing a cronjob entry for mysqldump is that you can set it to be a low priority task with ionice -c 3 nice 19. Combined with the --single-transaction option for InnoDB you can run backups that will not lock tables or lock out resources that might be needed elsewhere.
I have the following.
/etc/mysqlpwd
[mysql]
user=root
password=password
With the following alias.
alias 'mysql -p'='mysql --defaults-extra-file=/etc/mysqlpwd'
To do a restore I simply use:
mysql -p [database] [file.sql]
This is how I'm backing-up a MariaDB database using an expanding variable.
I'm using a "secrets" file in a Docker-Compose setup to keep passwords out of Git, so I just cat that in an expanding variable in the script.
NOTE: The below command is executed from the Docker host itself:
mysqldump -h192.168.1.2 -p"$(cat /docker-compose-directory/mariadb_root_password.txt)" -uroot DB-Name > /backupsDir/DB-Name_`date +%Y%m%d-%H:%M:%S`.sql
This is tested and known to work correctly in Ubuntu 20.04 LTS with mariadb-client.
I'm doing mine a different way, using Plink(Putty command line) to connect to remotehost, then the below command is in the plink file that runs on the remote server, then I use RSYNC from windows to get it and backup to an onprem NAS.
sudo mysqldump -u root --all-databases --events --routines --single-transaction > dump.sql
I have keys setup on the remote host and using PowerShell that's scheduled via task scheduler to run weekly.
what about --password=""
worked for me running on 5.1.51
mysqldump -h localhost -u <user> --password="<password>"
Definitely I think it would be better and safer to place the full cmd line in the root crontab , with credentails.
At least the crontab edit is restricred (readable) to someone who already knows the password.. so no worries to show it in plain text...
If needed more than a simple mysqldump... just place a bash script that accepts credentails as params and performs all amenities inside...
The bas file in simple
#!/bin/bash
mysqldump -u$1 -p$2 yourdbname > /your/path/save.sql
In the Crontab:
0 0 * * * bash /path/to/above/bash/file.sh root secretpwd 2>&1 /var/log/mycustomMysqlDump.log
You can specify the password on the command line as follows:
mysqldump -h <host> -u <user> -p<password> dumpfile
The options for mysqldump are Case Sensitive!