Backup MySQL users

后端 未结 8 2012
无人及你
无人及你 2021-01-31 09:15

How do I backup MySQL users and their privileges?

Anything like mysqldump?

I am looking for something like:

mysqldump -d -u root -p MyTable &         


        
相关标签:
8条回答
  • 2021-01-31 09:15

    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;

    0 讨论(0)
  • 2021-01-31 09:25
    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
    
    0 讨论(0)
  • 2021-01-31 09:31

    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...

    0 讨论(0)
  • 2021-01-31 09:31

    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.

    0 讨论(0)
  • 2021-01-31 09:34

    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

    0 讨论(0)
  • 2021-01-31 09:34

    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.

    0 讨论(0)
提交回复
热议问题