mysql 拷貝許可權 mysql使用者及許可權複製

2021-10-17 17:43:44 字數 2206 閱讀 6856

前言

由於某些很坑的原因,需要將一台mysql裡的全部資料進行遷移,並且需要遷移使用者及許可權。下面記錄下使用者及許可權是如何遷移的。

原理首先,我沒找到現成的工具。。。因此只好自己搞了,好在也沒多複雜。

使用者遷移

mysql裡的使用者都存在於mysql.user這張表裡。可以通過sql查詢這張表拿到host、user、authentication_string(加密後的密碼)。

然後通過sql在新庫中建立使用者,並更新新庫中的mysql.user表裡的authentication_string欄位。這樣就不需要知道賬號的明文密碼了。

需要注意的是,修改完mysql.user表中的加密密碼欄位後,需要執行

flush privileges

然後新的密碼才能生效

許可權遷移

利用sql語句

show grants for 'user'@'host';

可查詢指定使用者被授權過的許可權,得到的直接就是一條授權語句。將此授權語句在新庫中執行即可

需要注意的是授權語句中如果有針對某個表的授權,那麼當表不存在時會報錯,因此授權的遷移只能放在資料的遷移之後

完整示例指令碼

# coding:utf8

import pymysql

source_mysql_client = pymysql.connect(

host=none, user=none, password="", database=none, port=3306

source_mysql_client.autocommit(true)

source_mysql_cursor = source_mysql_client.cursor()

target_mysql_client = pymysql.connect(

host=none, user=none, password="", database=none, port=3306

target_mysql_client.autocommit(true)

target_mysql_cursor = target_mysql_client.cursor()

# 需要忽略的使用者

ignore_users = ["mysql.session", "root", "mysql.sys"]

target_sql_list =

sql = "select host, user, authentication_string from mysql.user"

source_mysql_cursor.execute(sql)

for host, user, authentication_string in source_mysql_cursor.fetchall():

if user in ignore_users:

continue

# 建立使用者

create_sql = "create user if not exists '{}'@'{}' identified by 'skvnajnvr92jkfads'".format(

user, host

# 修改密碼

change_password_sql = "update mysql.user set authentication_string='{}' where host='{}' and user='{}'".format(

authentication_string, host, user

# 授權語句獲取

grant_sql = "show grants for '{}'@'{}'".format(user, host)

source_mysql_cursor.execute(grant_sql)

grant_sql_result = source_mysql_cursor.fetchall()

target_sql_list.extend([x[0] for x in grant_sql_result])

source_mysql_cursor.close()

source_mysql_client.close()

for sql in target_sql_list:

r = target_mysql_cursor.execute(sql)

print(sql)

print(r)

target_mysql_cursor.close()

target_mysql_client.close()

mysql 重新整理許可權 mysql許可權

1,檢視所有使用者許可權 select distinct concat user user,host,as query from mysql.user 或者 select from mysql.user 2,檢視某乙個使用者的許可權 show grants for user ip 3,分配許可權 以...

mysql 許可權設定 mysql 許可權設定

關於mysql的使用者管理,筆記 1 建立新使用者 通過root使用者登入之後建立 grant all privileges on to testuser localhost identified by 123456 建立新使用者,使用者名為testuser,密碼為123456 grant all ...

mysql 列許可權 mysql 許可權相關

mysql許可權 1.資料庫 資料表 資料列許可權 alter 修改已存在的資料表 例如增加 刪除列 和索引。create 建立新的資料庫或資料表。delete 刪除表的記錄。drop 刪除資料表或資料庫。index 建立或刪除索引。insert 增加表的記錄。select 顯示 搜尋表的記錄。up...