Mysql Export user Rights
When migrating a MySQL database, it is sometimes necessary to migrate users and permissions in the source database. For this migration, we can obtain the relevant permissions of the user from the mysql.user table to generate the corresponding SQL statement, and then execute the generated SQL statement on the target server. This article provides a script to generate and demonstrate the extraction of user permissions.
1. Generate a script for user permissions
[root@db upload] # more exp_grant.sh
#! / bin/bash
# Function export user privileges
Pwd=123456
Expgrants ()
{
Mysql-B-upright root'-p$ {pwd}-N $@-e "SELECT CONCAT (
'SHOW GRANTS FOR', user,'@', host,'';'
) AS query FROM mysql.user "|\
Mysql-upright root'-p$ {pwd} $@ |\
Sed's /\ (GRANT. *\) /\ 1 Grants for. *\) /--\ 1 /; /-- / {x Tipp *\ x;}'
}
Expgrants >. / grants.sql
2. Generate permission SQL script
[root@db upload] #. / exp_grant.sh
[root@db upload] # cat grants.sql
-- Grants for root@127.0.0.1
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 root@172.16.10.%
GRANT ALL PRIVILEGES ON *. * 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
The generated script can be executed on the target server. Mysql-uname-ppwd