当前位置: 移动技术网 > IT编程>脚本编程>Python > python批量导出导入MySQL用户的方法

python批量导出导入MySQL用户的方法

2019年04月02日  | 移动技术网IT编程  | 我要评论

民事诉讼法2012,博古开来简历,子陵另类

数据库迁移(a -> b),需要把用户也迁移过去,而用户表(mysql.user)有上百个用户。有2种方法进行快速迁移:
1,在同版本的条件下,直接备份a服务器的mysql数据库,还原到b服务器。
2,要是不同版本的数据(5.1 -> 5.5),很可能mysql数据库下面的一些表结构,甚至表数据的默认值都不一样,按照1的方法进行迁移,虽然最后也是可以正常访问,但是还是有些不太放心,很可能会影响到了b服务器上的mysql,这样就需要用命令行来生成帐号了,这样是最安全和放心的。下面用python脚本来进行批量导出:

复制代码 代码如下:

#!/bin/env python
# -*- encoding: utf-8 -*-
#-----------------------------------------
# name:        mysql_user_dump.py
# purpose:     批量导出用户
# 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)

运行: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.%';

最后把这些命令在b上面执行就好了,也可以在执行脚本的时候重定向到一个sql文件:如:user.sql,在到b服务器的数据库里面执行source user.sql 就完成了导入工作。
第2个方法最好,不需要1里面的删表和重建表的操作,最安全。

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网