How to Export & Import Existing User (with its Privileges!)

后端 未结 9 2179
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-02-03 17:01

I have an existing MySQL instance (test), containing 2 databases and a few users each having different access privileges to each database.

I now need to duplicate one of

9条回答
  •  忘掉有多难
    2021-02-03 17:34

    Here's what I'm using these days as part of my daily backup scripts (requires root shell and MySQL access, linux shell, and uses the mysql built-in schema:

    First, I create a file /var/backup/mysqlroot.cnf containing the root password so I can automate my scripts and not hardcode any passwords in them:

    [client]
    password=(put your password here)
    

    Then I create an export script which dumps create user commands and grants like this:

    touch /var/backup/backup_sql.sh
    chmod 700 /var/backup/backup_sql.sh
    vi /var/backup/backup_sql.sh
    

    And then write the following contents:

    #!/bin/bash
    
    mysql --defaults-extra-file=/var/backup/mysqlroot.cnf -sNe " \
      SELECT \
        CONCAT( 'CREATE USER \'', User, '\'@\'', Host, '\' IDENTIFIED BY \'', authentication_string, '\'\;' ) AS User \
      FROM mysql.user \
      WHERE \
        User NOT LIKE 'mysql.%' AND CONCAT( User, Host ) <> 'rootlocalhost' AND User <> 'debian-sys-maint' \
    "
    
    mysql --defaults-extra-file=/var/backup/mysqlroot.cnf -sNe " \
      SELECT \
        CONCAT( '\'', User, '\'@\'', Host, '\'' ) as User FROM mysql.user \
      WHERE \
        User NOT LIKE 'mysql.%' \
        AND CONCAT( User, Host ) <> 'rootlocalhost' \
        AND User <> 'debian-sys-maint' \
    " | sort | while read u ; 
     do echo "-- $u"; mysql --defaults-extra-file=/var/backup/mysqlroot.cnf -sNe "show grants for $u" | sed 's/$/;/'
    done
    

    Then I just have to run it like this: /var/backup/backup_sql.sh > /tmp/exportusers.sql

提交回复
热议问题