如何在Linux中重置MySQL或者M(jìn)ariaDB的root密碼
如果你是***次設(shè)置 MySQL 或 MariaDB 數(shù)據(jù)庫,你可以直接運(yùn)行 mysql_secure_installation 來實(shí)現(xiàn)基本的安全設(shè)置。
其中一項(xiàng)是設(shè)置數(shù)據(jù)庫 root 帳戶的密碼 - 你必須保持私密,并僅在絕對(duì)需要時(shí)使用。如果你忘記了密碼或需要重置密碼(例如,當(dāng)數(shù)據(jù)庫管理員換人或被裁員!),這篇文章會(huì)派上用場(chǎng)。我們將解釋如何在 Linux 中重置或恢復(fù) MySQL 或 MariaDB 的 root 密碼。
建議閱讀: 更改 MySQL 或 MariaDB 的 root 密碼。
雖然我們將在本文中使用 MariaDB,但這些說明同樣也適用于 MySQL。
恢復(fù) MySQL 或者 MariaDB 的 root 密碼
開始之前,先停止數(shù)據(jù)庫服務(wù)并檢查服務(wù)狀態(tài),我們應(yīng)該可以看到先前設(shè)置的環(huán)境變量:
- ------------- SystemD -------------
- # systemctl stop mariadb
- ------------- SysVinit -------------
- # /etc/init.d/mysqld stop
接下來,用 --skip-grant-tables 選項(xiàng)啟動(dòng)服務(wù):
- ------------- SystemD -------------
- # systemctl set-environment MYSQLD_OPTS="--skip-grant-tables"
- # systemctl start mariadb
- # systemctl status mariadb
- ------------- SysVinit -------------
- # mysqld_safe --skip-grant-tables &
使用 skip tables 啟動(dòng) MySQL/MariaDB
這可以讓你不用 root 密碼就能連接到數(shù)據(jù)庫(你也許需要切換到另外一個(gè)終端上):
- # mysql -u root
接下來,按照下面列出的步驟來。
- MariaDB [(none)]> USE mysql;
- MariaDB [(none)]> UPDATE user SET password=PASSWORD('YourNewPasswordHere') WHERE User='root' AND Host = 'localhost';
- MariaDB [(none)]> FLUSH PRIVILEGES;
***,停止服務(wù),取消環(huán)境變量設(shè)置并再次啟動(dòng)服務(wù):
- ------------- SystemD -------------
- # systemctl stop mariadb
- # systemctl unset-environment MYSQLD_OPTS
- # systemctl start mariadb
- ------------- SysVinit -------------
- # /etc/init.d/mysql stop
- # /etc/init.d/mysql start
這可以讓先前的改變生效,允許你使用新的密碼連接到數(shù)據(jù)庫。
總結(jié)
本文我們討論了如何重置 MariaDB/MySQL 的 root 密碼。一如往常,如果你有任何問題或反饋請(qǐng)?jiān)谠u(píng)論欄中給我們留言。我們期待聽到你的聲音。
作者簡(jiǎn)介:
Gabriel Cánepa - 一位來自阿根廷圣路易斯梅塞德斯鎮(zhèn) (Villa Mercedes, San Luis, Argentina) 的 GNU/Linux 系統(tǒng)管理員,Web 開發(fā)者。就職于一家***級(jí)的消費(fèi)品公司,樂于在每天的工作中能使用 FOSS 工具來提高生產(chǎn)力。