详细出处参考:http://www.jb51.net/article/43294.htm
#!/usr/bin/env python #-*-encoding:utf-8-*- #------------------------- #name: mysql_usr_dump.py #Purpose: 批量导出用户 #Author: huangchengdu #-------------------------- 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='huang',db='mysql',port=3306,charset='utf-8') rows = get_data(conn) output_data(conn,rows)