在对MySQL进行迁移的时候,有时候也需要迁移源数据库内的用户与权限。对于这个迁移我们可以从.user表来获取用户的相关权限来生成相应的SQL语句,然后在目标服务器上来执行生成的SQL语句即可。本文提供了生成提取用户权限的脚本并给出演示。

1、生成用户权限的脚本

[[email protected] ~]# 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 /;/--/{x;p;x;}'
}
expgrants > ./grants.sql

2、生成权限SQL脚本

[[email protected] ~]# ./exp_grant.sh 

[[email protected] ~]# head grants.sql
-- Grants for  
GRANT ALL PRIVILEGES ON *.* TO 'root'@'127.0.0.1' IDENTIFIED BY PASSWORD '*EB3EA446C759C9DA93F84FCB56430DBEF051A9DD' WITH GRANT OPTION;
GRANT ALL PRIVILEGES ON `CNBO0815`.* TO 'root'@'127.0.0.1' WITH GRANT OPTION;

-- Grants for % 
GRANT ALL PRIVILEGES ON *.* TO 'root'@'172.16.10.%' IDENTIFIED BY PASSWORD '*6BB4837EB74329105EE4568DDA7DC67ED2CA2AD9';

-- Grants for % 
GRANT USAGE ON *.* TO 'CNBO'@'192.168.1.%' IDENTIFIED BY PASSWORD '*ABD91BAD4A3448428563952E281015B237310EA8';
         ...........................

--Author : Leshami
--Blog   : http://blog.csdn.net/leshami

3、在目标服务器上执行脚本

参考:

鹏城DBA总群