连接到您的数据库服务器并执行:
select concat('show grants for ','\'',user,'\'@\'',host,'\'') from mysql.user;
你会得到这样的东西:
+--------------------------------------------------------+
| concat('show grants for ','\'',user,'\'@\'',host,'\'') |
+--------------------------------------------------------+
| show grants for 'mariadb.sys'@'localhost' |
| show grants for 'mysql'@'localhost' |
| show grants for 'root'@'localhost' |
+--------------------------------------------------------+
将输出捕获到某个临时文件。
然后循环遍历该临时文件中的每一行,将其发送到您的 mysql 服务器,捕获输出。
输出将是您可以用来在另一台服务器上重建用户的东西:
GRANT ALL PRIVILEGES ON *.* TO `root`@`localhost` IDENTIFIED VIA mysql_native_password USING 'invalid' OR unix_socket WITH GRANT OPTION
GRANT PROXY ON ''@'%' TO 'root'@'localhost' WITH GRANT OPTION
这是我目前正在使用的脚本:
mysql -u${BACKUP_DB_USER} -p${BACKUP_DB_PASSWORD} -e"select concat('show grants for ','\'',user,'\'@\'',host,'\'') from mysql.user" > user_list_with_header.txt
sed '1d' user_list_with_header.txt > ./user.txt
while read user; do mysql -u${BACKUP_DB_USER} -p${BACKUP_DB_PASSWORD} -e"$user" > user_grant.txt; echo "-- ${user}" >> user_privileges.txt; sed '1d' user_grant.txt >> user_privileges.txt; done < user.txt
echo "flush privileges" >> user_privileges.txt;
awk '{print $0";"}' user_privileges.txt > all_user_privileges_final.sql
rm user.txt user_list_with_header.txt user_grant.txt user_privileges.txt
您将在文件 all_user_privileges_final.sql 中拥有所有授权声明。
当然,您可以将初始查询限制为仅列出您想要的用户。