Python bulk export methods for importing MySQL users

  • 2020-04-02 13:13:31
  • OfStack

Database migration (A - > B), users need to be migrated to the past, and the user table (mysql.user) has hundreds of users. There are two ways to do this:
1. Under the condition of the same version, directly backup the mysql database of server A and restore to server B.
2, if the different version of the data (5.1 - > 5.5), may be some of below the mysql database table structure, and even the defaults for the table data is different, according to the method of 1 for migration, while the last can be normal visit, but still some don't trust, is likely to be affected B mysql on the server, so you need to use the command line to generate account, this is the most safe and rest assured. The following python script is used for bulk export:


#!/bin/env python
# -*- encoding: utf-8 -*-
#-----------------------------------------
# Name:        mysql_user_dump.py
# Purpose:      Bulk export user 
# Author:      zhoujy
# Created:     2013-05-28
#-----------------------------------------
import MySQLdb
def get_data(conn):
    query  = 'select user,host from mysql.user order by user'
    cursor = conn.cursor()
    cursor.execute(query)
    lines  = cursor.fetchall()
    return lines
def output_data(conn,rows):
    for user,host in rows:
        query  = "show grants for '%s'@'%s'" %(user,host)
        cursor = conn.cursor()
        cursor.execute(query)
        show_pri = cursor.fetchall()
        for grants_command in show_pri:
            print ''.join(grants_command)+';'
        print ''
if __name__ =='__main__':
    conn = MySQLdb.connect(host='localhost',user='root',passwd='123456',db='mysql',port=3306,charset='utf8')
    rows  = get_data(conn)
    output_data(conn,rows)

Run: python mysql_user_dump. Py


GRANT REPLICATION SLAVE ON *.* TO 'rep'@'192.168.234.%' IDENTIFIED BY PASSWORD '*6BB4837EB74329105EE4568DDA7DC67ED2CA2AD9';
GRANT ALL PRIVILEGES ON *.* TO 'root'@'localhost' IDENTIFIED BY PASSWORD '*6BB4837EB74329105EE4568DDA7DC67ED2CA2AD9' WITH GRANT OPTION;
GRANT ALL PRIVILEGES ON *.* TO 'root'@'192.168.234.%' IDENTIFIED BY PASSWORD '*6BB4837EB74329105EE4568DDA7DC67ED2CA2AD9';
GRANT USAGE ON *.* TO 'test'@'192.168.234.%' IDENTIFIED BY PASSWORD '*2A032F7C5BA932872F0F045E0CF6B53CF702F2C5';
GRANT SELECT, INSERT, UPDATE, DELETE ON `test`.* TO 'test'@'192.168.234.%';
GRANT USAGE ON *.* TO 'zzz_test'@'192.168.234.%' IDENTIFIED BY PASSWORD '*2A032F7C5BA932872F0F045E0CF6B53CF702F2C5';
GRANT SELECT, INSERT, UPDATE, DELETE ON `zzz%`.* TO 'zzz_test'@'192.168.234.%';

Finally, execute these commands on B, or redirect to an SQL file when executing the script: for example :user.sql, execute the source user.sql in the database of B server to complete the import.
The second method is the best, do not need 1 inside the delete table and rebuild the operation of the table, the most secure.


Related articles: