且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

mysql授权和回收

更新时间:2022-10-03 18:09:26

mysql跟其他数据库一样可以为不同的用户分配不同的权限

基本的操作使用的是SQL中的Grant(分配权限)和Revoke(回收权限

一、关于Grant

Grant可以把指定的权限分配给特定的用户,如果这个用户不存在,则会创建一个用户

<a href="http://www.linuxso.com/command/" target="_blank"><span style="text-decoration: underline;">命令</span></a>格式

grant 权限 on 数据库名.表名 to 用户名@登陆方式 href="http://www.linuxso.com/command/id.html" target="_blank"><span style="text-decoration: underline;">id</span></a>entified by 'password1'

grant select,insert,up<a href="http://www.linuxso.com/command/date.html" target="_blank"><span style="text-decoration: underline;">date</span></a>,delete on auth.* to user1@localhost identified by 'password'

权    限:select,insert,update,delete,drop,ind<a href="http://www.linuxso.com/command/ex.html" target="_blank"><span style="text-decoration: underline;">ex</span></a>,all,privileges(表示赋予用户全部权限跟all一样)
数据库  :当数据库名称.表名称被*.*代替,表示用户拥有操作mysql上所有数据库所有表的权限        
登陆方式:即用户地址,可以是localhost,也可以是ip地址、机器名字、域名.也可以用'%'表示从任何地址连接
'password':可以为空,但是为空这表示只能从本地登陆,建议不能为空</p>
范例1:
授权数据库用户tom从本机访问MySQL服务器并拥有对auth数据库中所有表的完全权限
mysql&gt; grant all on auth.* TO tom@localhost identified by '123';
Query OK, 0 rows affected (0.00 sec)
mysql&gt; grant all on auth.* TO tom@'localhost' identified by "123";
小结:使用引号或双引号没有任何区别,主要是用于区别字符和命令
范例2:
授权数据库用户john从10.0.0.0/8 网络中连接到MySQL服务器,对auth数据库中所有表拥有完全权限
mysql&gt; grant all on auth.* to john@'10.0.0.0/8' identified by '123';
Query OK, 0 rows affected (0.00 sec)
<p>mysql&gt; grant all on auth.* TO tom@192.168.1.1 identified by '123';
Query OK, 0 rows affected (0.00 sec)
                        
mysql&gt; grant all privileges on *.* to 123ks@localhost identified by '123456';
Query OK, 0 rows affected (0.00 sec)</p>
小结:如果是指定了一个网段或网络范围的话,网段或网络范围需要加引号

二、关于Revoke
revoke的作用则是回收授于用户的权限
命令格式为:
revoke 权限 on 数据库名.表名 from 用户名@登陆方式;
范例3:
撤销用户tom从本机访问数据库auth的所有权限
mysql&gt; revoke all on auth.* from tom@'localhost';

Query OK, 0 rows affected (0.00 sec)

tom@*:*即登陆方式,有时候可能撤销的不是本地用户,要根据需要撤销

范例4:
撤销用户tom从任意地址访问数据库auth的所有权限

mysql&gt; revoke all on auth.* from tom@'%';

Query OK, 0 rows affected (0.00 sec)
范例5:
查看tom用户从本机连接是的权限
mysql&gt; show grants for tom@localhost;

范例6:
查看数据库auth中所有授权的用户

mysql&gt; select host,user,db from mysql.db where db='auth'; 这里没有使用use mysql 效果是跨库查表
范例7:
查看当前登陆用户的权限
mysql&gt; show grants;

范例8:

删除用户123cs@localhost
delete from mysql.user where user='123cs';
删除用户后使用show grant 查看该用户会发现能看到此用户的权限,那是因为并没有撤销他的权限
在MySQL中,用户信息存放在mysql.User中
灵活使用权限赋予和撤销,可以加深对SQL中的权限参数的理解,初学者不放试着多多练习,有助于在SQL上的理解
 


本文转自    geekwolf   51CTO博客,原文链接:http://blog.51cto.com/linuxgeek/997995