近期部署同学发现,使用我给的mysqldump出来的数据恢复完测试准生产环境后,login 总是报错Access denied for user 'phptest'@'localhost' (using password: YES)
flush privileges的作用
mysql 官方文档中针对flush privileges 的描述如下:
If you modify the grant tables directly using statements such as INSERT, UPDATE, or DELETE (which is not recommended), the changes have no effect on privilege checking until you either tell the server to reload the tables or restart it. Thus, if you change the grant tables directly but forget to reload them, the changes have no effect until you restart the server. This may leave you wondering why your changes seem to make no difference!
To tell the server to reload the grant tables, perform a flush-privileges operation. This can be done by issuing a FLUSH PRIVILEGES statement or by executing a mysqladmin flush-privileges or mysqladmin reload command.
简单点就是,当我们直接操作授权表之后,如:mysql.user
,是需要执行flush操作重新加载数据的。
思考:导入的mysqldump出来的备份中有授权,为什么还是登录失败?
备份中的授权语句
解答上面的问题很简单,看下dump出来的文件,找到对应的授权信息
LOCK TABLES `user` WRITE;
/*!40000 ALTER TABLE `user` DISABLE KEYS */;
INSERT INTO `user` VALUES (……
'%','phptest','N','N','N','N','N','N','N','N','N','N','N','N','N','N','N','N','N','N','N','N','N','N','N','N','N','N','N','N','N','','','','',0,0,0,0,'mysql_native_password','*BF6E67FD947536646304BBE1F81A8DC2D87A9CAC','N','2020-05-06 10:54:43',NULL,'N');
貌似一下就明了了,dump出来的数据就是对mysql user
表的数据转换成了insert
语句,所以,直接导入的时候,相当于对mysql user
表直接做了insert
操作,结合上面flush privileges
操作的使用场景,导入后,必须执行flush操作。
! 一个小技巧:
导出时,可以不导出user 表,
通过show grants for 和 select concat(’ identified by password ‘’,authentication_string,’’;’) from mysql.user where user =‘XXX’;
导出grant + identified 语句,在导入数据成功后,再导入权限信息。
执行flush privileges之后什么时候会生效
flush privileges
之后,对新如的连接,直接生效,对于现存的连接,如下操作时生效:
- 针对
表
和列
的权限,在下次客户端请求时生效 - 针对
库
的权限,再次use db
的时候生效 - 全局权限和密码修改,不影响现有连接,只有新连接进来时生效