MySQL 安全控制
DCL(Data Control Language 數(shù)據(jù)庫控制語言)
用于數(shù)據(jù)庫授權、角色控制等操作
GRANT 授權,為用戶賦予訪問權限
REVOKE 取消授權,撤回授權權限
用戶管理
創(chuàng)建用戶
create user '用戶名'@'IP地址' identified by '密碼';
刪除用戶
drop user '用戶名'@'IP地址';
修改用戶
rename user '用戶名'@'IP地址' to '新用戶名'@'IP地址' ;
修改密碼
// 第一種方法:
set password for '用戶名'@'IP地址'=Password('新密碼')
// 第二種方法:
alter user '用戶名'@'IP地址' identified by '新密碼';
// 第三種方法(忘記密碼時,必須使用此方法修改密碼):
UPDATE mysql.user SET authentication_string='' WHERE user='root' and host='localhost';
PS:用戶權限相關數(shù)據(jù)保存在mysql數(shù)據(jù)庫的user表中,所以也可以直接對其進行操作(不建議)
權限管理
grant 權限 on 數(shù)據(jù)庫.表 to '用戶'@'IP地址' identified by '密碼'; -- 授權并設置密碼
revoke 權限 on 數(shù)據(jù)庫.表 from '用戶'@'IP地址' -- 取消權限
查看授權信息
查看授權語句
show grants for '用戶'@'IP地址';
查看生效的授權信息
針對所有庫和表的權限,比如*.*。去mysql.user中查看
select * from mysql.user where user='shark'\G
針對具體到庫的權限,比如db_name.*。去mysql.db中查看
select * from mysql.db where user='shark'\G
針對具體表的授權,在 mysql.tables_priv中查看
select * from mysql.tables_priv where user='shark'\G
假如是沒有MySQL8.X
CREATE USER '你的用戶名'@'localhost' IDENTIFIED BY '你的密碼';
#創(chuàng)建新的用戶
GRANT ALL PRIVILEGES ON 你的數(shù)據(jù)庫名.* TO '你的用戶名'@'localhost';
#把剛剛創(chuàng)建的數(shù)據(jù)庫的管理權限給予剛剛創(chuàng)建的MySQL用戶
FLUSH PRIVILEGES;
#刷新權限,使用設置生效
關于權限
all privileges 除grant外的所有權限
select 僅查權限
select,insert 查和插入權限
...
usage 無訪問權限
alter 使用alter table
alter routine 使用alter procedure和drop procedure
create 使用create table
create routine 使用create procedure
create temporary tables 使用create temporary tables
create user 使用create user、drop user、rename user和revoke all privileges
create view 使用create view
delete 使用delete
drop 使用drop table
execute 使用call和存儲過程
file 使用select into outfile 和 load data infile
grant option 使用grant 和 revoke
index 使用index
insert 使用insert
lock tables 使用lock table
process 使用show full processlist
show databases 使用show databases
show view 使用show view
update 使用update
reload 使用flush
shutdown 使用mysqladmin shutdown(關閉MySQL)
super 使用change master、kill、logs、purge、master和set global。還允許mysqladmin調(diào)試登陸
replication client 服務器位置的訪問
replication slave 由復制從屬使用
關于數(shù)據(jù)庫和表
對于目標數(shù)據(jù)庫以及內(nèi)部其他:
數(shù)據(jù)庫名.* 數(shù)據(jù)庫中的所有
數(shù)據(jù)庫名.表 指定數(shù)據(jù)庫中的某張表
數(shù)據(jù)庫名.存儲過程 指定數(shù)據(jù)庫中的存儲過程
*.* 所有數(shù)據(jù)庫
關于用戶和IP
用戶名@IP地址 用戶只能在改IP下才能訪問
用戶名@192.168.1.% 用戶只能在改IP段下才能訪問(通配符%表示任意)
用戶名@%.shark.com
用戶名@% 用戶可以再任意IP下訪問(默認IP地址為%)
Example
create user 'shark'@'';
grant all privileges on *.* to 'shark'@'%' identified by '123';
立刻生效
/*將數(shù)據(jù)讀取到內(nèi)存中,從而立即生效。*/
flush privileges
也可以在創(chuàng)建用戶的同時直接授權(MySQL8.x 不可以)
grant select on *.* /*設置查詢數(shù)據(jù)的權限在所有的庫和表*/
to 'shark_2'@"%" /*指定用戶名和來源 ip*/
identified by '123'; /*設置密碼*/