When migrating to MySQL databases, it is sometimes necessary to migrate users and permissions within the source database. For this migration we can get the user's relevant permissions from the Mysql.user table to generate the corresponding SQL statements, and then execute the generated SQL statements on the target server. This article provides a script to generate the extraction user rights and gives a demo.
1. Script to generate user rights
Copy Code code as follows:
[Root@hkbo ~]# more exp_grant.sh
#!/bin/bash
#Function Export User Privileges
pwd=123456
Expgrants ()
{
Mysql-b-U ' root '-p${pwd}-N $@-E ' select CONCAT (
' Show grants for ', user, ' @ ', host, '; '
As Query from Mysql.user | \
Mysql-u ' root '-p${pwd} $@ | \
Sed ' s/\ (GRANT. *\)/\1;/;s/^\ (grants for. *\)/--\1;} '
}
Expgrants >/grants.sql
2. Generate Permissions SQL script
Copy Code code as follows:
[Root@hkbo ~]#./exp_grant.sh
[Root@hkbo ~]# head Grants.sql
--Grants for root@127.0.0.1
GRANT all Privileges "*.* to ' root" @ ' 127.0.0.1 ' identified by PASSWORD ' *EB3EA446C759C9DA93F84FCB56430DBEF051A9DD ' with GRANT OPTION;
Grant all privileges in ' CNBO0815 '. * to ' root ' @ ' 127.0.0.1 ' with GRANT OPTION;
--Grants for root@172.16.10.%
GRANT all Privileges "*.* to ' root" @ ' 172.16.10.% ' identified by PASSWORD ' *6bb4837eb74329105ee4568dda7dc67ed2ca2ad9 ';
--Grants for cnbo@192.168.1.%
GRANT USAGE on *.* to ' Cnbo ' @ ' 192.168.1.% ' identified by PASSWORD ' *abd91bad4a3448428563952e281015b237310ea8 ';
...........................
3, execute the script on the target server
Executes the generated script on the target server. Mysql-uname-ppwd <grants.sql
Need to note:
A, the target service is not a null server, there are already some accounts and permissions should be considered will cover the problem.
b, if you only need to migrate non-root users, you can add a filter condition in the original script, where user<> ' root '.