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
--ignore
to skip grants for certain users, or --only
to only include grants for certain users. Option syntax differs from mysqldump
in that --ask-pass
is its own option.
Jan 27, 2020 at 9:09
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;