天天看点

MySQL基础操作——密码相关的操作

作者:贺浦力特

通常MySQL密码相关操作有修改密码,重置密码,本次来记录下修改,重置密码,免密码连接。

之前还有一篇密码策略的文章。 MySQL实验之-密码策略在这儿, 就不赘述了

9de7bb31d0644e7393039222babfed10 欢迎收藏。

直奔主题,少废话, 欢迎关注。

修改密码的三种方法

set password='Root_1qaz';
alter user user() identified by 'Root_1qaz';
alter user 'root'@'localhost' identified by 'Root_1qaz';           

重置密码

密码忘记了,只能重置了, 重置可以这样操作

MySQL8(windows)重置密码

1. 关闭数据库, 以管理员的身份开启 cmd

2. 无密码启动: mysqld.exe --defaults-file="C:\ProgramData\MySQL\MySQL Server 8.0\my.ini" --console --skip-grant-tables --shared-memory

3. 以管理员的身份打开另外一个 cmd, 输入 mysql -uroot -p 要求输入密码时,直接回车免密登录

4. 清空密码: update mysql.user set authentication_string='' where user='root';

5. ctrl+C 关闭第一个 cmd, 退出 MySQL, 正常服务启动 MySQL

6. 输入 mysql -uroot -p 要求输入密码时, 由于root用户在前面被置为空, 直接回车免密登录

7. 修改密码

MySQL忘记root密码的两种解决方法

1. skip-grant-tables

在默认的参数文件中加上 skip-grant-tables 重启数据库

#运行mysql客户端,直接回车免密登录
mysql 
mysql> update mysql.user set authentication_string=password(newpwd) where user='root';
mysql> flush privileges;           

MySQL8中的变化:

● 加了 skip-grant-tables 参数后会自动加上 skip-networking 不允许远程连接

● 移除了 PASSWORD() 函数 修改密码的方法是用 alter user 的命令修改密码.但注意要载入权限表后才能 alter user

mysql> alter user root identified by 'newpwd';
ERROR 1290 (HY000): The MySOL server is running with the --skip-grant-tables option so it cannot execute this statement
mysql> flush privileges;
mysql> alter user root@localhost identified by 'newpwd';           

2. init-file

使用 -init-file 参数启动实例, 类似: mysqld_safe --init-file=/tmp/chpw.sql &

在chpw.sql 文件里面写上密码修改语句: alter user root@localhost identified by 'newpwd';

实例启动成功后, 密码即修改完毕 这种方法只会重启一次 MySOL 实例,而且基本上不存在安全隐患

免密码连接几种方法

方法1 设置在 /etc/my.cnf 或 $HOME/.my.cnf 中, 中括号可选 client 或 mysql,

区别是 client 适用于所有客户端, mysql 仅适用于mysql命令

cat > ~/.my.cnf <<EOF
[client]
password=Root_1qaz
user=root
EOF
chmod 400 ~/.my.cnf
mysql -h localhost -P 3306 -ur oot -D TEST           

方法2 省略 --login-path 则默认 login-path 名字为 client

mysql_config_editor set --login-path=bak1 --host=db01 --port=3307 --user=root --password
mysql_config_editor set --login-path=bak2 --socket=/u01/MySQL/3307/data/mysql.sock --user=root --password
mysql_config_editor print --all
mysql --login-path=test           

方法3 配置 auth_socket 使用操作系统验证

install plugin auth_socket soname 'auth_socket.so';
select * from mysql.plugin;
create user test identified with auth_socket as 'test';
select user,host,plugin,authentication_string from mysql.user where user='test';
mysql -u test #以操作系统 test 登陆           

方法4 试用客户端证书登录

见专题: MySQL使用客户端证书登录

继续阅读