导出MySQL用户权限

来源:互联网 发布:软件测试过程视频 编辑:程序博客网 时间:2024/06/05 14:59

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

1、生成用户权限的脚本

vi exp_grant.sh

#!/bin/bash

#Function export user privileges
pwd=123
sock=/tmp/mysql_smart.sock
expgrants()
{
  mysql -B -u'bohai' -p${pwd} -S $sock -N $@ -e "SELECT CONCAT(
    'SHOW GRANTS FOR ''', user, '''@''', host, ''';'
    ) AS query FROM mysql.user" | \
  mysql -u'bohai' -p${pwd} -S $sock $@ | \
  sed 's/\(GRANT .*\)/\1;/;s/^\(Grants for .*\)/-- \1 /;/--/{x;p;x;}'
}
expgrants > ./grants.sql

2、生成权限SQL脚本

[root@centos5 bh]# ./exp_grant.sh [root@centos5 bh]# lsexp_grant.sh  grants.sql[root@centos5 bh]# cat grants.sql -- Grants for wanghai@127.0.0.1 GRANT ALL PRIVILEGES ON *.* TO 'wanghai'@'127.0.0.1' IDENTIFIED BY PASSWORD '*82521E41E455B1A1DA5F92D052B213905F094343';-- Grants for zabbix@127.0.0.1 GRANT ALL PRIVILEGES ON *.* TO 'zabbix'@'127.0.0.1' IDENTIFIED BY PASSWORD '*5543250CB097E3A24E840791F9DFEFF5221B74DC';--author:薄刀刀--address:http://blog.csdn.net/bohai0409-- Grants for umcuser@192.168.1.59 GRANT USAGE ON *.* TO 'umcuser'@'192.168.1.59' IDENTIFIED BY PASSWORD '*7BE333EE54D41F1B2D8668616A748834B8E394F7';GRANT ALL PRIVILEGES ON `umc`.* TO 'umcuser'@'192.168.1.59';


3、在目标服务器上执行脚本
将生成的脚本在目标服务器上执行即可。 # mysql -ubodaodao -pbodaodao321 
-S /tmp/mysql_umc.sock <grants.sql
需要注意:
a、目标服务上为非空服务器,已经存在一些账户及权限应考虑会覆盖的问题。
b、如果仅仅需要迁移非root用户,可以在原脚本中添加过滤条件,即 where user<>'root' 。


3、遇到的问题

# sh exp_grant.sh ERROR 1141 (42000) at line 10: There is no such grant defined for user 'net' on host '192.168.10.*'mysql> show grants for net@'192.168.10.*'ERROR 1141 (42000): There is no such grant defined for user 'net' on host '192.168.10.*'mysql> delete  from mysql.user where user='net' and host='192.168.10.*';                         Query OK, 1 row affected (0.01 sec)

参考:
http://serverfault.com/questions/8860/how-can-i-export-the-privileges-from-mysql-and-then-import-to-a-new-server


0 0
原创粉丝点击