Sometimes we need to migrate our databases to a new MySQL server. It is easy to move the databases, but without the users and their permissions, our new databases would be worthless. Below is a step-by-step on migrating MySQL users to a new MySQL server
Step 1 – Create a Query List That We Can Use to Get Grants for All Users
I use these options so that I wouldn’t get any formatting characters that I would have to manually delete later.
-Nskip column names in the output
-ppassword – Asks me to type the password so nobody can get it from the command line history
-ssilent mode – less formatting output that we don’t want like “|” and “-“
So, let’s get a list of the users in a query that we can use to get the grants. Our query will be output into the “
$ mysql -uroot -N -p -s > myfile Enter password: select Distinct CONCAT(‘show grants for `’, user, ‘`@`’, host, ‘`;’) as query from mysql.user; quit
If we want to see what our query file look like, we can take a quick peek:
[root@classes-dev-mysql ~]# cat myfile show grants for `user1`@`%`; show grants for `user2`@`%`; show grants for `user3`@`10.%`; show grants for `user4`@`10.%`; show grants for `jeff`@`10.%`;
Step 2 – Create the MySQL Grant File
We don’t have quite what we want and need yet. We are looking for a query that will create all of our users on the new MySQL server. We need to run the query that we just created and it will give us the query that we will use later to create the users. It will create our grant permission statements in a file named “
[root@classes-dev-mysql ~]# mysql -uroot -N -p -s -r < myfile > grantfile Enter password:
We can take a peek at what our grantfile contains:
$ cat grantfile GRANT USAGE ON *.* TO ‘user1’@’%’ IDENTIFIED BY PASSWORD ‘5ea9af6g6t27032f’ GRANT ALL PRIVILEGES ON `database1`.* TO ‘user1’@’%’ GRANT USAGE ON *.* TO ‘user2’@’10.%’ IDENTIFIED BY PASSWORD ‘2a123b405cbfe27d’ GRANT SELECT ON `database1`.`table1` TO ‘user2’@’10.%’GRANT ALL PRIVILEGES ON *.* TO ‘user3’@’10.%’ IDENTIFIED BY PASSWORD ‘753af2za1be637ea’ GRANT SELECT, INSERT, UPDATE, DELETE ON *.* TO ‘user3’@’10.%’ IDENTIFIED BY PASSWORD ’08ad9be605rfgcb’…
Step 3 – Create Users and Grant MySQL Permissions on the New MySQL Machine
Now we are done working on the source machine. We need to copy our file named “
grantfile” over to the new machine.
$ scp grantfile firstname.lastname@example.org:/home/myuser
Next, we login to the destination or the new MySQL machine that we are building and run the “grantfile” in MySQL to create our users on the new MySQL machine.
$ mysql -uroot -p < ./grantfile
That’s it. As long as our databases are named the same in the new MySQL, our users should be ready to use the copy of the databases in the new MySQL machine.
Source: Uptime Made Easy