MySQL 的root 密碼忘了,不知道改怎麼辦,下面是修改root 密碼步驟。
(1)登錄到數據庫所在服務器,手工kill 掉MySQL 進程:
kill `cat /mysql-data-directory/hostname.pid`
其中,/mysql-data-directory/hostname.pid 指的是MySQL 數據目錄下的.pid 文件,它記錄了
MySQL 服務的進程號。
[[email protected] mysql]# kill `cat /data/mysql/maridb1.pid`
(2)使用—skip-grant-tables 選項重啓MySQL 服務:
[[email protected] mysql]# cd /usr/local/mysql/bin
[[email protected] bin]# mysqld_safe --skip-grant-tables --user=mysql &
其中--skip-grant-tables意思是啓動MySQL 服務的時候跳過權限表認證。
啓動後,連接到MySQL 的root 將不需要口令
查看服務是否啓動
[[email protected] ~]# ps -ef|grep mysql
root 3895 3056 0 11:16 pts/0 00:00:00 /bin/sh /usr/local/mysql/bin/mysqld_safe --skip-grant-tables --user=mysql
mysql 4045 3895 0 11:16 pts/0 00:00:00 /usr/local/mysql/bin/mysqld --basedir=/usr/local/mysql/ --datadir=/data/mysql --plugin-dir=/usr/local/mysql//lib/plugin --user=mysql --skip-grant-tables --log-error=/data/mysql/maridb1.err --pid-file=maridb1.pid --socket=/tmp/mysql.sock --port=3306
root 4172 4130 0 11:20 pts/1 00:00:00 grep --color=auto mysql
(3)用空密碼的root 用戶連接到MySQL,並且更改root 口令:
[[email protected] ~]# mysql -uroot
Welcome to the MariaDB monitor. Commands end with ; or /g.
Your MariaDB connection id is 9
Server version: 10.2.10-MariaDB-log MariaDB Server
Copyright (c) 2000, 2017, Oracle, MariaDB Corporation Ab and others.
Type 'help;' or '/h' for help. Type '/c' to clear the current input statement.
MariaDB [(none)]> set password = password('123');
ERROR 1290 (HY000): The MariaDB server is running with the --skip-grant-tables option so it cannot execute this statement
MariaDB [(none)]> use mysql
Database changed
MariaDB [mysql]> update user set password=password('root') where user='root' and host='localhost';
Query OK, 0 rows affected (0.00 sec)
Rows matched: 1 Changed: 0 Warnings: 0
此時,由於使用了--skip-grant-tables 選項啓動,使用“set password”命令更改密碼失敗,直
接更新user 表的password 字段後更改密碼成功。
(4)刷新權限表,使得權限認證重新生效:
MariaDB [mysql]> flush privileges;
Query OK, 0 rows affected (0.00 sec)
(5)重新用root 登錄時,必須輸入新口令:
[[email protected] ~]# mysql -uroot
ERROR 1045 (28000): Access denied for user 'root'@'localhost' (using password: NO)
[[email protected] ~]# mysql -uroot -proot
Welcome to the MariaDB monitor. Commands end with ; or /g.
Your MariaDB connection id is 12
Server version: 10.2.10-MariaDB-log MariaDB Server
Copyright (c) 2000, 2017, Oracle, MariaDB Corporation Ab and others.
Type 'help;' or '/h' for help. Type '/c' to clear the current input statement.
至此密碼修改成功