天天看点

MySQL 如何快速复制用户权限到其他环境

脚本用途:

 1、mysql主从搭建,从库用户权限的复制(可直接在主库执行脚本,将输出结果在从库执行)

 2、实现 pt-show-grants【打印权限信息】(线上可选择不用安装pt软件..通过脚本实现pt-show-grants功能)

 3、用户权限统计

<b>脚本:</b>

hostname=192.168.1.12

username=lottery

password=lottery

touch create_user.txt

for port in `ps -ef | grep mysql| grep socket| grep datadir| awk -f= '{print $nf}'`

  do

   sock=`ps -ef | grep mysql| grep socket| grep datadir|awk -f".pid" '{print $nf}'| grep $port`

   echo "-------"$port"-create_user.sql:-------" &gt;&gt;create_user.txt

     echo "select concat('show grants for ''',user,'''@''',host, ''';') from mysql.user where user &lt;&gt;'root' and user &lt;&gt;'' " | \

     mysql --host=$hostname --user=$username --password=$password $sock -n | \

     sed "s/$/;/"  &gt;&gt;create_user.txt

done

cat create_user.txt

rm -rf create_user.txt

<b></b>

<b>脚本打印信息如下:</b>

-------3306-create_user.sql:-------

grant all privileges on *.* to 'lottery'@'192.168.%' identified by password '*6e9ef176abe11111146af84111111171111111';

grant replication slave, replication client on *.* to 'repl'@'192.168.1.%' identified by password '*ac111111fddc8943ab31cbd111111e79f7953ea';

grant replication slave, replication client on *.* to 'repl'@'192.168.2%' identified by password '*ac2111111fddc8943a11111147d758e79f7953ea';

grant usage on *.* to 'zabbix'@'localhost' identified by password '*6bb4837eb74329101111118dda7dc61111112ad9';

-------3308-create_user.sql:-------

grant replication slave on *.* to 'repl'@'%' identified by password '*ac241830ffddc11111131cbd47d758e79111111a';

grant all privileges on *.* to 'lottery'@'192.168.%' identified by password '*6e9ef111111590a33746af84db6348d171111111';

grant select, insert, update, delete on *.* to 'mycat'@'192.168.1.%' identified by password '*6ea111111950b4a6bfc111111925fd11111147a42';

grant select, insert, update, delete on *.* to 'mycat_user'@'192.168.1%' identified by password '*6eaf111111b4a6bfc92ba04111111086111111112';

grant shutdown on *.* to 'admin'@'localhost' identified by password '*4e74b1831111113952f4c163cb961dfbc5111111';

[root@miu-mysql-002 ~]# 

<b>pt-show-grants 打印权限介绍</b>

l 功能介绍:

规范化和打印 mysql权限,让你在复制、比较 mysql权限以及进行版本控制的时候更有效率!

l 用法介绍:

pt-show-grants [option...] [dsn] 选项自行用help 查看,dsn 选项也请查看help,选项区分大小写。

l 使用示例:

查看指定mysql的所有用户权限: pt-show-grants --host='localhost' --user='root' --password='zhang@123' 

查看执行数据库的权限: pt-show-grants --host='localhost' --user='root' --password='zhang@123' --database='hostsops' 

查看每个用户权限生成 revoke收回权限的语句: pt-show-grants --host='localhost' --user='root' --password='zhang@123' --revoke

【源于本人笔记】 若有书写错误,表达错误,请指正... 

继续阅读