Backup all privileges related to specific user of MySQL - mysql

I want to backup all privileges related to specific user (for example u_1) from a MySQL database and restore that in another server. As described here, The 'mysql' database contains users/privileges/passwords. So I have to backup all related data from all tables of mysql database (mysql.user,mysql.db, ...). I can run this command:
$ mysqldump -u root --flush-privileges -r mysql.sql -p mysql
But of course the mysql.sql contains all users and all privileges.
Also I tried this command:
$ mysqldump -u root -p --where="user.user='u_1'" mysql user> mysql.sql
But as expected, it only contains a row of mysql.user table.
Is there a way to strip out other users except of u_1?

Try these options (line breaks for clarity):
$ mysqldump -u root -p
--where="user='u_1'"
--complete-insert
--extended-insert
--no-create-info
mysql
user db tables_priv columns_priv procs_priv proxies_priv
> mysql.sql
Or... let's call the above solution "the hard way."
This should be the easy way:
$ mysql -u root -p
--skip-column-names
-e "SHOW GRANTS FOR 'u_1';"
> grants.sql

I would use:
pt-show-grants --only u_1
pt-show-grants is a tool in the free Percona Toolkit.
See https://www.percona.com/doc/percona-toolkit/LATEST/pt-show-grants.html

Related

How to backup mysql using mysqldump?

I am new to using mysql and i am trying to backup a mysql database using mysqldump.
So this is what i have done so far:-
I ssh'ed into my VM and run mysql to get into the mysql CLI
Then i ran the command mysql> SHOW DATABASES; which gives me the following output :-
information|
| rap_songs|
| celebrities|
Now i am trying to backup my rap songs database and i run the following command :-
mysql> mysqldump -u root -p rap_songs > rap_songs_backup.sql
But nothing happens after this step. What am i doing wrong? Any help will be appreciated. thank you.
Run mysqldump in SSH terminal not in mysql terminal
For all database::
mysqldump --all-databases --single-transaction -u root -p > /all_databases.sql
For one database (rap_song in this case)::
mysqldump -u root -p rap_songs > /your_backup.sql
Now you need to go to / to see your files, mysqldump usually show nothing once its done terminal again avail for new cmd. So if terminal is again avail it means its done!
Non-root user | Permission denied error!
Don't use /your_backup.sql
use ~/your_backup.sql instead
~/ is your user data directory
Mysqldump without password
You can create a .my.cnf in ~/
[mysqldump]
user=mysqluser
password=userpass
Then chmod 600 ~/.my.cnf
now in your script or crontab don't mention -p or --password and when your cron or script execute it will automatically pick password from here
Okay so I had to run this query in order to circumvent the errors :-
mysqldump --complete-insert --routines --triggers --single-transaction
rap_songs> rap_songs_backup.sql

creating mysqldump to backup database

I know how mysqldump works.
But dont know where to use it?
If I execute this command after starting mysql program then it says error.
I am using ubuntu. So how can I use this utility?
Backup your database this way too..
mysql -u root -p DB_NAME > db_name_backup.sql
If you want to backup all database simply run this
mysql -u root -p > mysql_db_backup.sql
You will learn more about mysql and mysqldump here..
Guide:
mysqldump and mysql
MySQL Database Backup using mysqldump
shell> mysqldump --opt db_name > backup-file.sql
You can read the dump file back into the server like this:
shell> mysql db_name < backup-file.sql
Or like this:
shell> mysql -e "source /path-to-backup/backup-file.sql" db_name
mysqldump is also very useful for populating databases by copying data
from one MySQL server to another:
shell> mysqldump --opt db_name | mysql --host=remote_host -C db_name
It is possible to dump several databases with one command:
shell> mysqldump --databases db_name1 [db_name2 ...] > my_databases.sql
If you want to dump all databases, use the --all-databases option:
shell> mysqldump --all-databases > all_databases.sql
If tables are stored in the InnoDB storage engine, mysqldump provides a
way of making an online backup of these (see command below). This
backup just needs to acquire a global read lock on all tables (using
FLUSH TABLES WITH READ LOCK) at the beginning of the dump. As soon as
this lock has been acquired, the binary log coordinates are read and
lock is released. So if and only if one long updating statement is
running when the FLUSH... is issued, the MySQL server may get stalled
until that long statement finishes, and then the dump becomes
lock-free. So if the MySQL server receives only short (in the sense of
"short execution time") updating statements, even if there are plenty
of them, the initial lock period should not be noticeable.
shell> mysqldump --all-databases --single-transaction > all_databases.sql
For point-in-time recovery (also known as “roll-forward”, when you need
to restore an old backup and replay the changes which happened since
that backup), it is often useful to rotate the binary log (see
Section 8.4, “The Binary Log”) or at least know the binary log
coordinates to which the dump corresponds:
shell> mysqldump --all-databases --master-data=2 > all_databases.sql
or
shell> mysqldump --all-databases --flush-logs --master-data=2 > all_databases.sql
The simultaneous use of --master-data and --single-transaction works as
of MySQL 4.1.8. It provides a convenient way to make an online backup
suitable for point-in-time recovery if tables are stored in the InnoDB
storage engine.
For more information on making backups, see Section 6.1, “Database
Backups”.
mysqldump -u MYSQL_USER -h MYSQL_SERVER -pMYSQL_PASS --all-databases > "dbs.sql"
You use it directly on the terminal, just like mysql it self, and pass the parameters directly to it.
mysqldump -u [user] -p[password] [database name] > dumpfilename.sql
yes you can.
see http://dev.mysql.com/doc/refman/5.0/en/mysqldump.html for more information on the tool.
If it's an entire DB, then:
$ mysqldump -u [uname] -p[pass] db_name > db_backup.sql
If it's all DBs, then:
$ mysqldump -u [uname] -p[pass] --all-databases > all_db_backup.sql
If it's specific tables within a DB, then:
$ mysqldump -u [uname] -p[pass] db_name table1 table2 >
table_backup.sql
You can even go as far as auto-compressing the output using gzip (if your DB is very big):
$ mysqldump -u [uname] -p[pass] db_name | gzip > db_backup.sql.gz
If you want to do this remotely and you have the access to the server in question, then the following would work (presuming the MySQL server is on port 3306):
$ mysqldump -P 3306 -h [ip_address] -u [uname] -p[pass] db_name >
db_backup.sql
To IMPORT:
ype the following command to import sql data file:
$ mysql -u username -p -h localhost DATA-BASE-NAME < data.sql
In this example, import 'data.sql' file into 'blog' database using vivek as username:
$ mysql -u sat -p -h localhost blog < data.sql
If you have a dedicated database server, replace localhost hostname with with actual server name or IP address as follows:
$ mysql -u username -p -h 202.54.1.10 databasename < data.sql
OR use hostname such as mysql.cyberciti.biz
$ mysql -u username -p -h mysql.cyberciti.biz database-name < data.sql
If you do not know the database name or database name is included in sql dump you can try out something as follows:
$ mysql -u username -p -h 202.54.1.10 < data.sql
REfer: http://dev.mysql.com/doc/refman/5.6/en/mysqldump.html

How to use MySQL dump from a remote machine

How can I backup a mysql database which is running on a remote server, I need to store the back up file in the local pc.
Try it with Mysqldump
#mysqldump --host=the.remotedatabase.com -u yourusername -p yourdatabasename > /User/backups/adump.sql
Have you got access to SSH?
You can use this command in shell to backup an entire database:
mysqldump -u [username] -p[password] [databasename] > [filename.sql]
This is actually one command followed by the > operator, which says, "take the output of the previous command and store it in this file."
Note: The lack of a space between -p and the mysql password is not a typo. However, if you leave the -p flag present, but the actual password blank then you will be prompted for your password. Sometimes this is recommended to keep passwords out of your bash history.
No one mentions anything about the --single-transaction option. People should use it by default for InnoDB tables to ensure data consistency. In this case:
mysqldump --single-transaction -h [remoteserver.com] -u [username] -p [password] [yourdatabase] > [dump_file.sql]
This makes sure the dump is run in a single transaction that's isolated from the others, preventing backup of a partial transaction.
For instance, consider you have a game server where people can purchase gears with their account credits. There are essentially 2 operations against the database:
Deduct the amount from their credits
Add the gear to their arsenal
Now if the dump happens in between these operations, the next time you restore the backup would result in the user losing the purchased item, because the second operation isn't dumped in the SQL dump file.
While it's just an option, there are basically not much of a reason why you don't use this option with mysqldump.
This topic shows up on the first page of my google result, so here's a little useful tip for new comers.
You could also dump the sql and gzip it in one line:
mysqldump -u [username] -p[password] [database_name] | gzip > [filename.sql.gz]
mysqldump -h [domain name/ip] -u [username] -p[password] [databasename] > [filename.sql]
Tried all the combinations here, but this worked for me:
mysqldump -u root -p --default-character-set=utf8mb4 [DATABASE TO BE COPIED NAME] > [NEW DATABASE NAME]
If you haven't install mysql_client yet and using Docker container instead:
sudo docker exec MySQL_CONTAINER_NAME /usr/bin/mysqldump --host=192.168.1.1 -u username --password=password db_name > dump.sql
You can directly pipe it to the remote server where you wish to copy your data to:
mysqldump -u your_db_user_name -p --set-gtid-purged=OFF --triggers --routines --events --compress --skip-lock-tables --verbose your_local_sql_db_name | mysql -u your_db_user_name -p -h your_remote_server_ip your_remote_server_db_name
You need to have created the db on your remote sql server.
Using the above command, I was able to copy from my local sql server version 8.0.23 to my remote sqlserver running 8.0.25
This is how you would restore a backup after you successfully backup your .sql file
mysql -u [username] [databasename]
And choose your sql file with this command:
source MY-BACKED-UP-DATABASE-FILE.sql

Using mysqldump and database users

I'm attempting to assemble all the options that I need for mysqldump to create everything used by my applications database into a single script. This includes the database itself and all the database users/passwords/privileges.
I've got it all figured out with the exception of the user piece... here's what I'm currently using:
mysqldump -h host -u root -p \
--add-drop-database --routines -B database_name > backup.sql
So, what am I missing?
The database users/passwords/privileges are kept in the mysql database, and won't get dumped with your dump command. You'll have to add that database as well to the list of DBs to dump:
mysqldump ... --routines --databases database_name mysql > backup.sql
or just dump everything:
mysqldump ... --routines --all-databases > backup.sql
When dumping the mysql database, don't forget:
--flush-privileges Emit a FLUSH PRIVILEGES statement after dumping the mysql
database. This option should be used any time the dump
contains the mysql database and any other database that
depends on the data in the mysql database for proper
restore.
So, I had a fundamental misunderstanding. Users are not specific to a database, but are rather created at the server level.
You can view all existing users with the following query:
SELECT * FROM mysql.user;
Knowing this, it's pretty obvious that mysqldump shouldn't do anything with users. However, if you need an answer to exporting/importing users and perms I suggest you check the following article - it helped me out.
http://pento.net/2009/03/12/backing-up-permissions-for-individual-databases/
My apologies for the noise on the board, but I figured I'd leave the post incase anyone else has the same misunderstanding.
Full process for me when migrating from one Mac OS X dev environment to a new one.
0) Get rid of newer version of MySQL on new MacBook
I had accidentally installed MySQL 8, so I had to remove it because it was newer than my old MacBook.
# Remove binaries
$ brew uninstall mysql
# Remove data/config that is leftover
$ rm -r /usr/local/var/mysql/
1) Install same version of MySQL on new MacBook
# Install version that matched old MacBook
$ brew install mysql#5.7
# Because it is an old version, you have to do a special configuration step
$ echo 'export PATH="/usr/local/opt/mysql#5.7/bin:$PATH"' >> ~/.bash_profile
$ source ~/.bash_profile
# Start server
$ mysql.server start
2) Dump data on old MacBook
$ mysqldump -uroot --flush-privileges --routines --all-databases > complete_dump.sql
3) Restore data on new MacBook
$ mysql -p -uroot < complete_dump.sql
You may want to take a look at mysqlpump, it can dump all databases, and can export the users as CREATE USER and GRANT statements instead of relying on the mysql system db + mysql_upgrade.
mysqlpump # Dumps (almost) all databases (see [2])
mysqlpump --exclude-databases=% --users # Dumps all user accounts
It's unclear from the docs if you can do mysqlpump --users and get both all databases and the users.
Some system tables get omitted by default, see restrictions.
mysqldump version 10.19 contains the option --system=users wich adds CREATE USER with the GRANT commands into the dump.
mysqldump -h host -u root -p \
--add-drop-database --routines -B database_name \
--system=users > backup.sql
source: https://mariadb.com/kb/en/mysqldump/
Connect to your database server and execute:
select concat('show grants for ','\'',user,'\'#\'',host,'\'') from mysql.user;
You'll get something like this:
+--------------------------------------------------------+
| concat('show grants for ','\'',user,'\'#\'',host,'\'') |
+--------------------------------------------------------+
| show grants for 'mariadb.sys'#'localhost' |
| show grants for 'mysql'#'localhost' |
| show grants for 'root'#'localhost' |
+--------------------------------------------------------+
Capture the output to some temporary file.
And then cycle through each line in that temporary file, sending it against your mysql server, capturing the output.
Output will be something that you can use to reconstruct users on another server:
GRANT ALL PRIVILEGES ON *.* TO `root`#`localhost` IDENTIFIED VIA mysql_native_password USING 'invalid' OR unix_socket WITH GRANT OPTION
GRANT PROXY ON ''#'%' TO 'root'#'localhost' WITH GRANT OPTION
Here's a script I'm currently using:
mysql -u${BACKUP_DB_USER} -p${BACKUP_DB_PASSWORD} -e"select concat('show grants for ','\'',user,'\'#\'',host,'\'') from mysql.user" > user_list_with_header.txt
sed '1d' user_list_with_header.txt > ./user.txt
while read user; do mysql -u${BACKUP_DB_USER} -p${BACKUP_DB_PASSWORD} -e"$user" > user_grant.txt; echo "-- ${user}" >> user_privileges.txt; sed '1d' user_grant.txt >> user_privileges.txt; done < user.txt
echo "flush privileges" >> user_privileges.txt;
awk '{print $0";"}' user_privileges.txt > all_user_privileges_final.sql
rm user.txt user_list_with_header.txt user_grant.txt user_privileges.txt
You'll have all grant statements in the file all_user_privileges_final.sql.
Of course, you can limit your initial query to list only user(s) you want.
You can only use the option --system=users to get the user's dump from mysql/MariaDB if mysql client is for MariaDB.
For example:
check mysql --version. If output is like mysql Ver 15.1 Distrib 10.6.8-MariaDB then
mysqldump -h <hostname> -u <usename> -p --system=users > mysqldb_users.sql

Backup MySQL users

How do I backup MySQL users and their privileges?
Anything like mysqldump?
I am looking for something like:
mysqldump -d -u root -p MyTable > Schema.sql
mysql -BNe "select concat('\'',user,'\'#\'',host,'\'') from mysql.user where user != 'root'" | \
while read uh; do mysql -BNe "show grants for $uh" | sed 's/$/;/; s/\\\\/\\/g'; done > grants.sql
You can backup mysql database using
mysqldump -u root -p mysql > mysql.sql
and restore mysql database by executing
mysql -uroot -p mysql < mysql.sql
Dont forget to
FLUSH PRIVILEGES
after restoring dump.
Hope it helps...
So far my experience with MySQL i didn't see anything to backup user and their privileges through a command line.
But i can backup those critical data by backing up mysql
mysqldump -u root -p mysql > mysql.sql
Percona has a great tool for this. pt-show-grants will dump users and their permissions so you can easily reload them.
https://www.percona.com/doc/percona-toolkit/LATEST/pt-show-grants.html
The users and privileges are stored in the databased named 'mysql'. You can use mysqldump to backup the tables in the databased named 'mysql'.
Good practice is using script for daily backup MySQL users and their privileges.
Take take a look on a one:
#!/bin/sh
HOSTNAME="localhost"
mysql -h $HOSTNAME -B -N -e "SELECT CONCAT('\'', user,'\'#\'', host, '\'') FROM user WHERE user != 'debian-sys-maint' AND user != 'root' AND user != ''" mysql > mysql_all_users_$HOSTNAME.txt
while read line; do mysql -h $HOSTNAME -B -N -e "SHOW GRANTS FOR $line"; done < mysql_all_users_$HOSTNAME.txt > mysql_all_users_$HOSTNAME.sql
sed -i.bak 's/$/;/' mysql_all_users_$HOSTNAME.sql
rm mysql_all_users_$HOSTNAME.txt
rm mysql_all_users_$HOSTNAME.sql.bak
Result of this script will be mysqldump file with users and privileges.
P.S. If your MySQL requires password - put -p or -u username -p after mysql -h $HOSTNAME in two places.
The scripts given above give the general idea, but they're inefficient. They're forking/execing mysql n+1 times. It can be done in only two calls to mysql
mysql ${logininfo} -B -N -e "SELECT CONCAT('\'',user,'\'#\'',host,'\'') from user where user != 'root'" mysql | \
while read uh
do
echo "SHOW GRANTS FOR ${uh};"
done | mysql ${logininfo} -B -N | sed -e 's/$/;/' > ${outfile}
If there are users other than root that you don't want to backup use or and specify user != 'whatever' in the where clause of the first mysql call.
probably pretty obvious for mysql command liners but for #spirit's answer above had to add -u root -ppassword after both mysql commands
mysql -u root -ppassword -BNe "select concat(''',user,''#'',host,''') from mysql.user where user != 'root'" | while read uh; do mysql -u root -ppassword -BNe "show grants for $uh" | sed 's/$/;/; s/\\/\/g'; done > grants.sql;