Take the 2-minute tour ×
Server Fault is a question and answer site for professional system and network administrators. It's 100% free, no registration required.

I know how to export/import the databases using mysqldump & that's fine but how do I get the privileges into the new server.

For extra points, there are a couple of existing databases on the new one already, how do I import the old servers privileges without nuking the couple existing of ones.

Old server: 5.0.67-community

New server: 5.0.51a-24+lenny1

EDIT: I've got a dump of the db 'mysql' from the Old Server & now want to know the proper way to merge with the 'mysql' db on the New Server.

I tried a straight 'Import' using phpMyAdmin and ended up with an error regarding a duplicate (one that I've already migrated manually).

Anyone got an elegant way of merging the two 'mysql' databases?

share|improve this question
    
1. Is it a requirement for you to use PHPMyAdmin? If it is I will write some PHPMyAdmin specific instructions for you. 2. From PHPMyAdmin if you try to "select * from mysql.user limit 1;" do you get results or an error. –  Richard Bronosky Jun 11 '09 at 20:35
1  
As I mentioned below, I think Richard's mygrants script is a good way to get grant info. However, you can also try editing the dump file to comment out INSERTs to the user table for users who already exist. Privileges for the dbs restored from the old server will then be copied. If you've already assigned privileges manually for some of the dbs you restored to the new box, look for these table names in the privilege files and comment these out, too. Don't forget a flush_privileges afterwards. Good description of the mysql db at: grahamwideman.com/gw/tech/mysql/perms/index.htm –  nedm Jun 13 '09 at 10:37
    
Great info in that link, thanks. Bookmarked. –  Richard Bronosky Jun 13 '09 at 13:10
add comment

9 Answers

up vote 92 down vote accepted

Do not mess with the mysql db. There is a lot more going on there than just the users table. Your best bet is the "SHOW GRANTS FOR" command. I have a lot of CLI maintenance aliases and functions in my .bashrc (actually my .bash_aliases that I source in my .bashrc). This function:

mygrants()
{
  mysql -B -N $@ -e "SELECT DISTINCT CONCAT(
    'SHOW GRANTS FOR \'', user, '\'@\'', host, '\';'
    ) AS query FROM mysql.user" | \
  mysql $@ | \
  sed 's/\(GRANT .*\)/\1;/;s/^\(Grants for .*\)/## \1 ##/;/##/{x;p;x;}'
}

The first mysql command uses SQL to generate valid SQL which is piped to the second mysql command. The output is then piped through sed to add pretty comments.

The $@ in the command will allow you to call it as: mygrants --host=prod-db1 --user=admin --password=secret

You can use your full unix tool kit on this like so:

mygrants --host=prod-db1 --user=admin --password=secret | grep rails_admin | mysql --host=staging-db1 --user=admin --password=secret

That is THE right way to move users. Your MySQL ACL is modified with pure SQL.

share|improve this answer
    
This is actually a nice bash helper function that works great. Take the output from that and be able to run on the new server and the privileges would be entered properly and accurately. –  Jeremy Bouse Jun 11 '09 at 14:12
1  
I love your function, today it saved me a lot of work. Thank you, thank you, thank you... –  Fabio Feb 15 '11 at 22:32
    
Love it. This has saved me at least an hour of work! –  wolfgangsz Jul 1 '11 at 12:50
    
This is great but it has one big flaw. An extra "\" is added to underscores in database names, so if you have for example a user with specific privileges on a database called foo_bar, it will be rendered as foo\_bar instead of foo_bar, so that won't be imported correctly. At least, this happens if you save the output from you script into a SQL file and then import it into the new server. I haven't tried the direct piping of export and import in a single line. –  matteo Oct 15 '13 at 9:41
add comment

There are two methods for extracting SQL Grants from a MySQL Instance

METHOD #1

You can use pt-show-grants from Percona Toolkit

MYSQL_CONN="-uroot -ppassword"
pt-show-grants ${MYSQL_CONN} > MySQLUserGrants.sql

METHOD #2

You can emulate pt-show-grants with the following

MYSQL_CONN="-uroot -ppassword"
mysql ${MYSQL_CONN} --skip-column-names -A -e"SELECT CONCAT('SHOW GRANTS FOR ''',user,'''@''',host,''';') FROM mysql.user WHERE user<>''" | mysql ${MYSQL_CONN} --skip-column-names -A | sed 's/$/;/g' > MySQLUserGrants.sql

Either method will produce a pure SQL dump of the MySQL grants. All there is left to do is to execute the script on a new server:

mysql -uroot -p -A < MySQLUserGrants.sql

Give it a Try !!!

share|improve this answer
add comment

You can mysqldump the 'mysql' database and import to the new one; a flush_privileges or restart will be required and you'll definitely want to back up the existing mysq db first.

To avoid removing your existing privileges, make sure to append rather than replace rows in the privilege tables (db, columns_priv, host, func, etc.).

share|improve this answer
    
Thanks @nedm. Seems like the annoying cPanel server I'm trying to get the dbs off doesn't show the db 'mysql'. Otherwise I'd test and affirm your answer. Once I figure that out I'll check back. Thanks. –  gyaresu May 16 '09 at 8:49
    
That is unfortunate but understandable, you are probably prevented from accessing any database but the ones directly owned by your user on a shared db. –  Dave Cheney May 17 '09 at 6:05
    
Ouch, yeah, without access to 'mysql' it will be difficult to do anything related to users or permissions. Do you have command line access? Can you run mysqldump from the terminal or command line (NOT from the mysql shell)? mysqldump -u username -ppassword mysql > mysqldump.sql –  nedm May 18 '09 at 17:08
    
The db 'mysql' was accessible from the Cpanel WHM if I logged in as 'root'. From there I can access a version of phpmyadmin which has the 'mysql' database containing permissions –  gyaresu Jun 10 '09 at 7:53
    
Merging into a existing mysql schema, data extracted from a mysql schema via mysqldump is almost certain to be problematic. You are manipulating a complex schema with enforced relationships, etc. This schema is so complex, in fact, that they created dedicated SQL syntax (GRANT, REVOKE, DROP USER, etc.) for dealing with it. Your extract, however, consists of only INSERT statements. I'm running out of characters here. Need I continue? –  Richard Bronosky Jun 13 '09 at 3:52
show 2 more comments

Or, utilize percona-toolkit (former maatkit) and use pt-show-grants (or mt-show-grants) for that purpose. No need for cumbersome scripts and/or stored procedures.

share|improve this answer
add comment

Richard Bronosky's answer was extremely useful for me. Many thanks!!!

Here is a small variation which was useful for me. It is helpful for transfering users e.g. between two Ubuntu installations running phpmyadmin. Just dump privileges for all users apart from root, phpmyadmin and debian-sys-maint. The code is then

mygrants()
{
mysql -B -N $@ -e "SELECT DISTINCT CONCAT(
'SHOW GRANTS FOR ''', user, '''@''', host, ''';'
) AS query FROM mysql.user WHERE user NOT IN ('root','phpmyadmin','debian-sys-maint')"  | \
mysql $@ | \
sed 's/\(GRANT .*\)/\1;/;s/^\(Grants for .*\)/## \1 ##/;/##/{x;p;x;}'
}
share|improve this answer
    
thanks for this „no brainer“ improvement. :) –  ThorstenS Mar 28 '13 at 21:21
add comment

How about a PHP script? :)

View source on this script and you have all the privilidges listed:

//connect
mysql_select_db("mysql", mysql_connect("localhost","root",""));

//create grants select statements
$rs = mysql_query("SELECT DISTINCT CONCAT('SHOW GRANTS FOR ''', user, '''@''', host, ''';') AS query FROM user");

//iterate through grants
while ($row=mysql_fetch_array($rs)) {
    //run grant query
    $rs2 = mysql_query($row['query']);
    //iterate through results
    while($row2 = mysql_fetch_array($rs2)){
        //print results
        echo $row2[0] . ";\n\n";
    }
}
share|improve this answer
add comment

You could also do it as a stored procedure:

CREATE PROCEDURE spShowGrants()
    READS SQL DATA
    COMMENT 'Show GRANT statements for users'
BEGIN
    DECLARE v VARCHAR(64) CHARACTER SET utf8;
    DECLARE c CURSOR FOR
    SELECT DISTINCT CONCAT(
        'SHOW GRANTS FOR ', user, '@', host, ';'
    ) AS query FROM mysql.user;
    DECLARE EXIT HANDLER FOR NOT FOUND BEGIN END;  
    OPEN c;
    WHILE TRUE DO
        FETCH c INTO v;
        SET @v = v;
        PREPARE stmt FROM @v;
        EXECUTE stmt;
    END WHILE;
    CLOSE c;
END

and call it with

$ mysql -p -e "CALL spShowGrants" mysql

then pipe the output through Richards sed command to get a backup of the privileges.

share|improve this answer
add comment

While it appears @Richard Bronosky's answer is the correct one, I came across this question after trying to migrate a set of databases from one server to another and the solution was much simpler:

server1$ mysqldump -u root -p --all-databases > dbdump.sql

server2$ mysql -u root -p < dbdump.sql

At this point, all my data was visible if I logged in as root, the mysql.user table had everything in it I was expecting, but I couldn't log in as any of the other users and found this question assuming I'd have to re-issue the GRANT statements.

However, it turns out that the mysql server simply needed to be restarted for the updated privileges in the mysql.* tables to take effect:

server2$ sudo restart mysql

Hopefully that helps someone else achieve what should be a simple task!

share|improve this answer
    
Oh, and my situation was slightly different to the OP's, in that I wasn't trying to merge a dump into a server with existing databases/users. –  Tom Sep 3 '11 at 1:17
2  
You don't actually have to restart MySQLd to 'update the privileges'. It can be done with the MySQL command 'flush privileges;' –  CloudWeavers May 3 '12 at 18:16
add comment

create a shell script file with the following code:

##############################################3
echo "SELECT DISTINCT CONCAT (\"show grants for '\", user, \"'@'\", host, \"';\") AS query FROM mysql.user; " >   script.sql    
echo "*** You will be asked to enter the root password twice ******"    
mysql -u root -p  < script.sql > output.sql ;    
cat output.sql | grep show > output1.sql  ; rm output.sql -f ; 
mysql -u root -p  < output1.sql > output.sql ;
clear
echo "-----Exported Grants-----"    
cat  output.sql ; rm  output.sql   output1.sql -f    
echo "-------------------------"
rm  script.sql -f
#

*then run it on the shell like this: you will be asked to enter the root password twice and then the GRANTS SQL will be displayed on the screen.*

share|improve this answer
add comment

protected by Chris S May 3 '12 at 18:25

Thank you for your interest in this question. Because it has attracted low-quality answers, posting an answer now requires 10 reputation on this site.

Would you like to answer one of these unanswered questions instead?

Not the answer you're looking for? Browse other questions tagged or ask your own question.