一台久未登录的测试服务器忘记了 MySQL root 密码,重置过程如下:先在 /etc/my.cnf 的 [mysqld] 小节添加 skip-grant-tables=1,让 mysqld 启动时不进行密码验证,然后重启 mysqld 服务,直接用 mysql -u root 免密登录,切换到 mysql 库执行 update user set authentication_string = password('newrootpassword'), password_expired = 'N', password_last_changed = now() where user = 'root'; 即可更新密码。
需要注意的是,MySQL 5.7 中密码字段名已由早期版本的 password 改为 authentication_string,语句中要对应修改。更新完成后退出 mysql,把 /etc/my.cnf 里刚加的 skip-grant-tables=1 删掉并再次重启 mysqld,最后用新密码登录验证即可。整个流程核心就是利用跳过授权表临时绕过验证,改完密码后再恢复配置,注意务必记得移除该行以免留下安全隐患。