HowTo: Migrate / Move MySQL Database And Users To New Server

I already wrote about how to move or migrate user accounts from old Linux / UNIX server to a new server including mails and home directories. However, in reality you also need to move MySQL database which may host your blog, forum or just your data stored in MySQL database. The mysqldump command will only export the data and the table structure but it will not include a users grants and privileges. The main function of the MySQL privilege system (which is stored in mysql.user table) is to authenticate a user who connects from a given host and to associate that user with privileges on a database such as SELECT, INSERT, UPDATE, and DELETE.


Our Sample Setup

  | db1 | -------------------------> -+
  +-----+                             |
   old mysql server                   |
   (                      |
  +-----+                             |        ///////////////////////////////
  | db2 | -------------------------> -+------> // Internet (ISP router      //
  +-----+                             |        // with port 80 forwarding)  //
   new mysql server                   |        ///////////////////////////////
   (                     |
  +-----+                             |
  | www1| -------------------------> -+
    Apache web server

You need to move db1 server database called blogdb and its users to db2 server.

Install MySQL On DB2

Use the apt-get or yum command to install mysql on DB2 server:
$ sudo apt-get install mysql-server mysql-client
$ sudo service mysql start
# set root password for new installation
$ mysqladmin -u root password NEWPASSWORD

$ sudo yum install mysql-server mysql
$ sudo chkconfig mysql on
$ sudo service mysql start
# set root password for new installation
$ mysqladmin -u root password NEWPASSWORD

Make sure OpenSSH server is also installed on DB2.

Get Current MySQL, Usernames, Hostname, And Database Names

Type the following command at shell prompt to list username and hostname list, enter:

mysql -u root -B -N -p -e "SELECT user, host FROM user" mysql

Sample outputs:

root	localhost

The first column is mysql username and second one is network host names. Now, type the following command to get exact details about grants and password for each user from above list:

mysql -u root -p -B -N -e"SHOW GRANTS FOR 'userName'@hostName"
mysql -u root -p -B -N -e"SHOW GRANTS FOR 'vivek'@"

Sample outputs:

GRANT USAGE ON *.* TO 'vivek'@'' IDENTIFIED BY PASSWORD 'somePasswordMd5'
GRANT ALL PRIVILEGES ON `blogdb`.* TO 'vivek'@''


  • vivek – MySQL login username
  • – Another server or workstation to access this mysql server
  • somePasswordMd5 – Password stored in mysql database which is not in a clear text format
  • blogdb – Your database name

Now, you’ve all info and you can move database and users to a new server called db2 as follows using the combination of OpenSSH ssh client and mysql clients as follows:

ssh user@db2 mysql -u root -p'password' -e "create database IF NOT EXISTS blogdb;"
ssh user@db2 mysql -u root -p'password' -e "GRANT USAGE ON *.* TO 'vivek'@'' IDENTIFIED BY PASSWORD 'somePasswordMd5';"
ssh user@db2 mysql -u root -p'password' -e "GRANT ALL PRIVILEGES ON `blogdb`.* TO 'vivek'@'';"
mysqldump -u root -p'password' -h 'localhost' blogdb | ssh user@db2 mysql -u root -p'password' blogdb

You can test it as follows from Apache web server:
$ mysql -u vivek -h -p blogdb -e 'show tables;'

A Note About Web Applications

Finally, you need to make changes to your application to point out to new a database server called DB2. For example, change the following from:

        $DB_SERVER = "";
        $DB_USER = "vivek";
        $DB_PASS = "your-password";
        $DB_NAME = "blogdb";


        $DB_SERVER = "";
        $DB_USER = "vivek";
        $DB_PASS = "your-password";
        $DB_NAME = "blogdb";

A Sample Shell Script To Migrate Database

# Copyright (c) 2005 nixCraft project <>
# This script is licensed under GNU GPL version 2.0 or above
# Author Vivek Gite <>
# ------------------------------------------------------------
# SETME First - local mysql user/pass
# SETME First - remote mysql user/pass
# SETME First - remote mysql ssh info
# Make sure ssh keys are set
# sql file to hold grants and db info locally
#### No editing below #####
# Input data
# Die if no input given
[ $# -eq 0 ] && { echo "Usage: $0 MySQLDatabaseName MySQLUserName"; exit 1; }
# Make sure you can connect to local db server
mysqladmin -u "$_lusr" -p"$_lpass" -h "$_lhost"  ping &>/dev/null || { echo "Error: Mysql server is not online or set correct values for _lusr, _lpass, and _lhost"; exit 2; }
# Make sure database exists
mysql -u "$_lusr" -p"$_lpass" -h "$_lhost" -N -B  -e'show databases;' | grep -q "^${_db}$" ||  { echo "Error: Database $_db not found."; exit 3; }
##### Step 1: Okay build .sql file with db and users, password info ####
echo "*** Getting info about $_db..."
echo "create database IF NOT EXISTS $_db; " > "$_tmp"
# Build mysql query to grab all privs and user@host combo for given db_username
mysql -u "$_lusr" -p"$_lpass" -h "$_lhost" -B -N \
-e "SELECT DISTINCT CONCAT('SHOW GRANTS FOR ''',user,'''@''',host,''';') AS query FROM user" \
mysql \
| mysql  -u "$_lusr" -p"$_lpass" -h "$_lhost" \
| grep  "$_user" \
|  sed 's/Grants for .*/#### &/' >> "$_tmp"
##### Step 2: send .sql file to remote server ####
echo "*** Creating $_db on ${rsshhost}..."
scp "$_tmp" ${_rsshusr}@${_rsshhost}:/tmp/
#### Step 3: Create db and load users into remote db server ####
ssh ${_rsshusr}@${_rsshhost} mysql -u "$_rusr" -p"$_rpass" -h "$_rhost" < "$_tmp"
#### Step 4: Send mysql database and all data ####
echo "*** Exporting $_db from $HOSTNAME to ${_rsshhost}..."
mysqldump -u "$_lusr" -p"$_lpass" -h "$_lhost" "$_db" | ssh ${_rsshusr}@${_rsshhost} mysql -u  -u "$_rusr" -p"$_rpass" -h "$_rhost" "$_db"
rm -f "$_tmp"

How Do I Use This Script?

Download the above script and edit it to set the following as per your setup:

# SETME First - local mysql DB1 admin user/password

# SETME First - remote mysql DB2 admin user/password

# Remote SSH Server (DB2 SSH Server)
# Make sure ssh keys are set

In this example, migrate a database called wiki with wikiuser username:
$ ./ wiki wikiuser

Server moved – 14/July/2010

Dear User,

In the last two days nixcraft moved to the new server (details about our older setup are here). No data is lost and most of the stuff is back as usual. The new server is much more stable. However, required libraries for RSS feed and PDF file generation code are not installed. I will fixed it ASAP. If any one see any other errors or 404 errors, please send me an email at Please ignore rss feed which is currently showing all old entires in your feed. My apologies for the temporary inconvenience and flooding your rss feed and inbox. The IPv6 AAAA entries will be published later on this weekend.

Thanks for all your support!

–Vivek Gite

πŸ₯Ί Was this helpful? Please add a comment to show your appreciation or feedback.

nixCrat Tux Pixel Penguin
Hi! 🀠
I'm Vivek Gite, and I write about Linux, macOS, Unix, IT, programming, infosec, and open source. Subscribe to my RSS feed or email newsletter for updates.

19 comments… add one
  • el*Loco Jul 13, 2010 @ 22:25

    You know mk-show-grants from maatkit?

    • πŸ›‘οΈ Vivek Gite (Author and Admin) nixCraft Jul 13, 2010 @ 22:43

      Naa, never used it. Thanks for sharing it.

  • yayabaobao Jul 14, 2010 @ 5:27


  • sem007 Jul 14, 2010 @ 7:04

    Right medicine at right time.

  • Shantanu Oak Jul 14, 2010 @ 15:36

    You have copied a single user from the DB1 database, but what about other users for e.g. ‘tom’ and ‘blog’ ? There must be some way to push the entire grants table to the new server.
    If ‘blogdb’ is the only database, you can safely omit it from mysqldump statement and it will include the required permissions table in the dump, that will be copied to the db2 server.

    • πŸ›‘οΈ Vivek Gite (Author and Admin) nixCraft Jul 14, 2010 @ 16:09

      You can just repeat the commands to add rest of the users or use the script which copies all users.

  • kelsey Aug 5, 2010 @ 10:02

    Excellent article, just referred it to my blog. thx

  • OmahaJohn Mar 31, 2011 @ 21:52

    Really good stuff. I’d love to see version two where this is put into a loop, where you “SELECT user, host FROM mysql.users;” and then iterate through the recordset returned, running the rest of your code on each record you get back.

    Regardless, fantastic stuff!

  • Sylwit Sep 16, 2011 @ 16:10

    You have a mistake on the line

    mysqldump -u “$_lusr” -p”$_lpass” -h “$_lhost” “$_db” | ssh ${_rsshusr}@${_rsshhost} mysql -u -u “$_rusr” -p”$_rpass” -h “$_rhost” “$_db”

    twice -u

    Great job. I had to modify it a bit and I will give you my version soon, Hope it will help someone.

  • Sylwit Sep 19, 2011 @ 14:16

    Here is it

    The README explains what did I change

    Thank you for this work Vivek

    • Tamnais Jan 8, 2012 @ 14:05

      Works like a charm! Thanks!

      Noticed a typo in line 71:
      echo “*** Creating $_db on ${rsshhost}…”
      missing “_”

      Also I have added ${_key} since I use several custom-named ssh keys:
      add -i ${_key} to ssh/scp commands

  • Jay Versluis Jan 1, 2012 @ 3:13

    Vivek, Sylwit,

    you’re both my heros πŸ˜‰ This tool works like a charm – thank you so much for both your hard work!

    Happy New Year 2012!!

  • Peter Dec 13, 2012 @ 16:04

    Vivek, thanks for your work. However, I found the restriction to a single user name not very useful, so I rewrote parts of the script in order to make it automatically determine and save all mysql user accounts that have privileges on the given database. Now, its usage looks like this: `./ myDB`. Another missbehaviour I noticed is that the grant statements aren’t terminated by a semicolon what of course results in MySQL errors on the remote machine. Dunno if I am the only one who noticed that, however Γ’β‚¬β€œ I also fixed this.

    You can find the updated script here:

  • Eddy Oct 21, 2013 @ 20:23

    First of all, love the script.

    I am in the middle of migrating ~200 databases to my new server and have run into a little problem, the script fails if there is a – in the name of the database. It escape everything before the – and throws a database not found error. any fixes?

    • Eddy Oct 22, 2013 @ 12:30

      I’ve drilled into this and it seems that the issue occurs when running the db create sql statement.

  • Greg Dec 4, 2013 @ 13:45

    for migrate/move databases, i use :
    on the source server
    1) Generate script create database

    mysql -u youradmin -B -N  -e "select concat('CREATE DATABASE ',SCHEMA_NAME,' DEFAULT CHARACTER SET ',DEFAULT_CHARACTER_SET_NAME,' COLLATE ',DEFAULT_COLLATION_NAME,';') from SCHEMATA where SCHEMA_NAME not in('information_schema','mysql','performance_schema','test'); " information_schema > cr_database.sql

    2) Generate script create users :

    mysql -u youradmin -B -N  -e "select distinct(concat('CREATE USER ',user,';')) from user where user is not null and user != '%' order by user " mysql > cr_user.sql

    3) Generate script for grant 1

    mysql -u youradmin -B -N  -e "select concat('SHOW GRANTS FOR '',user,''@'',host,'';') from user where user is not null order by user " mysql > cr_grant.sql

    4) Generate script forr grant 2

    mysql -u youradmin -B -N  --force mysql  lance_grant.sql

    On the target :
    1) cr_database.sql
    2) cr_user.sql
    3) Import with your backups
    4) lance_grant.sql

    Hope that help

    • Silviu Aug 26, 2014 @ 8:59

      This looks awesome, however step 4 is not working, I think it is missing at least a “>” in “… mysql > lance_grant.sql”.
      Any help on this?

      • Sof Sep 18, 2014 @ 15:36

        Last step don’t work because there is no command is the step 4. Even if you add the missing output symbol “>”, the file lance_grant.sql will be empty.

      • Sof Sep 18, 2014 @ 15:46

        My apologize !
        It will only export the “mysql” database.

Leave a Reply

Your email address will not be published. Required fields are marked *

Use HTML <pre>...</pre> for code samples. Your comment will appear only after approval by the site admin.