- Сброс пароля root в MySQL на Ubuntu
- Общая информация
- Требования для сброса пароля
- Сброс пароля root
- План сброса
- Определение версии MySQL
- Остановка сервера
- Отключение привилегий MySQL сервера
- Изменение пароля root пользователя MySQL
- Изменение пароля для MySQL 5.7.6 и новее
- Изменения пароля на MySQL 5.7.5 и позднее
- Завершение
- Восстановление привилегий и запуск сервера MySQL
- Проверка нового пароля
- Как изменить пароль пользователя на новых версиях MySQL
- Как изменить (сбросить) root пароль в MySQL
- Как поменять пароль root в MySQL
- Если пароль root ИЗВЕСТЕН
- Если пароль root НЕ ИЗВЕСТЕН
- How to Change Root Password of MySQL or MariaDB in Linux
- Change MySQL or MariaDB Root Password
- If You Appreciate What We Do Here On TecMint, You Should Consider:
- MySQL Change root Password
- Method #1: Use mysqladmin command to change root password
- Sample live session from my home server using mysqladmin
- How do I verify that the new password is working or not?
- A note about changing MySQL password for other users
- Method #2 : Changing MySQL root user password using the mysql command
- Login to mysql server, type the following command at shell prompt:
- Use mysql database (type command at mysql> prompt):
- Change password for user nixcraft, enter:
- Finally, reload the privileges:
- Sample live session from my home server
Сброс пароля root в MySQL на Ubuntu
Общая информация
Сбросить пароль root пользователю базы данных MySQL может потребоваться в случае, если потерян доступ к системе управления базами данных.
Требования для сброса пароля
- Локальный доступ или подключение по SSH к серверу на Ubuntu Linux.
- Предустановленная система СУБД MySQL с отсутствующим доступом.
Сброс пароля root
План сброса
Определение версии MySQL
Стоит сразу определить установленную версию MySQL, поскольку на разных версиях программы, команды, в дальнейшем, могут отличаться.
Для определения версии MySQL в терминале достаточно ввести команду:
Должен появится похожий вывод:
Строку можно сохранить в текстовом документе, чтобы не забыть версию MySQL.
Остановка сервера
Для отключения привилегий нужно остановить сервер MySQL, введя в терминале команду:
После выполнения команды процесс сервера MySQL будет приостановлен.
Отключение привилегий MySQL сервера
Отключение привилегий СУБД – исключение из процесса загрузки Grant-таблиц, которые хранят данные для авторизации пользователей (пароли и логины). Это позволит выполнить вход в MySQL без авторизации и восстановить пароль root по умолчанию.
Для начала создаётся конфигурационный файл, который изменяет параметры запуска MySQL. Для этого нужно ввести в терминале команду:
В созданный текстовой файл нужно внести следующие строки, которые ограничат загрузку Grant-таблиц и запретят выход в сеть (для обеспечения безопасности):
Для сохранения изменений в файле нужно нажать «CTRL+X», потом «Y» и подтвердить изменения нажатием «Enter».
Для применения изменений в процессе загрузки MySQL, нужно обновить конфигурацию Systemd командой:
Остаётся запустить сервер MySQL с отключенными привилегиями. Для этого в терминале вводится команда:
Изменение пароля root пользователя MySQL
Таблицы привилегий отключены и ничего не мешает выполнить вход в консоль MySQL от имени root пользователя без авторизации.
Для выполнения входа в консоль MySQL нужно ввести команду:
Авторизация должна пройти без введения пароля.
Для того чтобы сменить пароль пользователя root, нужно загрузить Grant-таблицы, введя команду в терминал MySQL:
Изменение пароля для MySQL 5.7.6 и новее
Смена пароля root пользователя в консоли MySQL выполняется последовательным введением следующих команд:
Вместо «MY_NEW_PASSWORD» вводится собственный пароль. Не стоит забывать о безопасности и ставить лёгкие пароли, так как это сыграет на руку злоумышленникам.
Изменения пароля на MySQL 5.7.5 и позднее
Нужно последовательно ввести следующие команды:
В поле «MY_NEW_PASSWORD» вводится собственный пароль.
Завершение
В случае успеха, в обоих случаях, будет получен следующий вывод:
Восстановление привилегий и запуск сервера MySQL
После изменения пароля необходимо восстановить параметры загрузки сервера MySQL, удалив конфигурацию Systemd. Для этого в терминале последовательно вводятся команды:
Далее необходимо перезапустить сервер MySQL со стандартными параметрами. Перезагрузка выполняется следующей командой:
Проверка нового пароля
Проверить новый пароль можно, выполнив вход в консоль MySQL от имени root пользователя:
Как изменить пароль пользователя на новых версиях MySQL
В последних выпусках MySQL была добавлена возможность входа без пароля, если системная учётная запись имеет root доступ.
Чтобы узнать пароль на новых версиях, достаточно в терминале ввести команду, которая запустит MySQL с правами администратора:
При получении ошибки «access denied» стоит переходить к описанному выше способу – «Сброс пароля root».
Если доступ к консоли получен успешно получен, можно выполнить сброс пароля root в Ubuntu для MySQL, последовательно вводя следующие команды:
В поле «new_password» вводится новый пароль для пользователя root.
Для применения изменений нужно перезагрузить таблицы привилегий следующей командой:
В случае успеха будет получен следующий вывод:
Начни экономить на хостинге сейчас — 14 дней бесплатно!
Источник
Как изменить (сбросить) root пароль в MySQL
Довольно часто происходит такая ситуация, что пароль для учетной записи root в MySQL необходимо восстановить, поменять или сбросить. Хорошо, если он известен, но бывают случаи, когда пароль был утерян или неизвестен с самого начала. В данной статье пойдет речь о том, как этот пароль восстановить, имея доступ к серверу, на котором запущен mysql-server для обоих случаев, когда пароль о учетной записи root ИЗВЕСТЕН и НЕ ИЗВЕСТЕН.
Как поменять пароль root в MySQL
Если пароль root ИЗВЕСТЕН
Возьмем самую простую ситуацию, когда пароль от учетной записи root вам известен и все что нужно сделать, это просто его поменять. Чтобы задать новый пароль для учетной записи root, необходимо проделать следующие действия:
1) Подключаемся в консоль MySQL сервера с правами root (не забываем ввести пароль, после появления соответствующего запроса):
2) Меняем пароль для пользователя root:
Для MySQL версий 5.7.6 и новее (5.7.7, 5.7.8. )
Для MySQL версий 5.7.5 и старее (5.7.4, 5.7.3. )
NEW_PASSWORD — это пароль, который вам необходимо поменять на свой собственный.
В результате выполнения данной команды, мы должны получить вот такой вывод в консоли:
В том случае, если указанные выше команды по какой то причине не сработали, вы можете воспользоваться следующим запросом:
В результате выполнения данной команды, мы должны получить вот такой вывод в консоли:
3) Перезагружаем привилегии, чтобы изменения вступили в силу:
4) Для выхода из консоли MySQL сервера выполняем команду выхода:
После этого, пароль должен поменяться.
Если пароль root НЕ ИЗВЕСТЕН
Если вы не знаете текущий пароль root (потеряли, забыли) в MySQL, то придется пойти чуть более сложным путем, чем описанные действия выше:
1) Останавливаем mysqld:
2) Проверяем, что нет запущенных процессов mysqld:
Если все нормально, то вывод команды должен состоять лишь из одной строки, примерно такого содержания:
3) Создаем каталог /var/run/mysqld для запуска mysqld в safe режиме из консоли
4) Делаем владельцем данного каталога пользователя mysql (чтобы не было проблем с правами)
5) Запускаем MySQL в ручном режиме из консоли, пропуская проверку прав (опция —skip-grant-tables). А также отключаем доступ к серверу через TCP/IP (с помощью опци и —skip-networking), чтобы злоумышленник не мог воспользоваться тем, что мы отключили проверку прав пользователей. При использовании данной опции, доступ к серверу становится возможным только через localhost.
В случае успешного запуска, вывод в консоли должен быть примерно таким:
6) Подключаемся из консоли к серверу mysqld и выбираем базу данных mysql:
7) Используем плагин mysql_native_password, иначе в некоторых случаях будем получать ошибку «ERROR 1524 (HY000): Plugin ‘auth_socket’ is not loaded«, а нам это не нужно:
Вывод в результате выполнения данной команды должен быть примерно таким:
8) Перезагружаем привилегии:
9) Меняем пароль для нужного пользователя, в нашем случае это root:
Для MySQL версий 5.7.6 и новее (5.7.7, 5.7.8. )
Для MySQL версий 5.7.5 и старее (5.7.4, 5.7.3. )
NEW_PASSWORD — это пароль, который вам необходимо поменять на свой собственный.
В результате выполнения данной команды, мы должны получить вот такой вывод в консоли:
В том случае, если указанные выше команды по какой то причине не сработали, вы можете воспользоваться следующим запросом:
В результате выполнения данной команды, мы должны получить вот такой вывод в консоли:
9) После чего, вводим команду exit для отключения:
10) Выключаем запущенный в ручном режиме Mysqld сервер:
Если все пройдет успешно, то вывод должен быть примерно таким:
Если же команда не сработала и вы получаете вот такую (или любую другую) ошибку:
То можно принудительно завершить процесс с помощью следующей команды:
11) Проверяем, что нет запущенных процессов mysqld:
Если все нормально, то вывод команды должен состоять лишь из одной строки, примерно такого содержания:
12) Запускаем Mysql-server в нормальном режиме:
И пытаемся подключиться к нашему серверу с новым паролем, который мы установили.
Источник
How to Change Root Password of MySQL or MariaDB in Linux
If you’re installing MySQL or MariaDB in Linux for the first time, chances are you will be executing mysql_secure_installation script to secure your MySQL installation with basic settings.
One of these settings is, database root password – which you must keep secret and use only when it is required. If you need to change it (for example, when a database administrator changes roles – or is laid off!).
This article will come in handy. We will explain how to change a root password of MySQL or MariaDB database server in Linux.
Although we will use a MariaDB server in this article, the instructions should work for MySQL as well.
Change MySQL or MariaDB Root Password
You know the root password and want to reset it, in this case, let’s make sure MariaDB is running:
Check MySQL Status
If the above command does not return the word active as output or its stopped, you will need to start the database service before proceeding:
Next, we will login to the database server as root:
For compatibility across versions, we will use the following statement to update the user table in the mysql database. Note that you need to replace YourPasswordHere with the new password you have chosen for root.
To validate, exit your current MariaDB session by typing.
and then press Enter. You should now be able to connect to the server using the new password.
Change MySQL/MariaDB Root Password
Summary
In this article we have explained how to change the MariaDB / MySQL root password – whether you know the current one or not.
As always, feel free to drop us a note if you have any questions or feedback using our comment form below. We look forward to hearing from you!
If You Appreciate What We Do Here On TecMint, You Should Consider:
TecMint is the fastest growing and most trusted community site for any kind of Linux Articles, Guides and Books on the web. Millions of people visit TecMint! to search or browse the thousands of published articles available FREELY to all.
If you like what you are reading, please consider buying us a coffee ( or 2 ) as a token of appreciation.
We are thankful for your never ending support.
Источник
MySQL Change root Password
Setting up MySQL password is one of the essential tasks. By default, root user is MySQL admin account user. Please note that the Linux or UNIX root account for your operating system and MySQL root user accounts are different. They are separate, and nothing to do with each other. Sometime you may remove Mysql root account and setup admin user as super user for security purpose.
[donotprint]
Tutorial details | |
---|---|
Difficulty level | Easy |
Root privileges | No |
Requirements | mysqladmin/mysql |
Est. reading time | N/A |
[/donotprint]
Method #1: Use mysqladmin command to change root password
If you have never set a root password for MySQL server, the server does not require a password at all for connecting as root. To setup root password for first time, use mysqladmin command at shell prompt as follows:
$ mysqladmin -u root password NEWPASSWORD
However, if you want to change (or update) a root password, then you need to use the following command:
$ mysqladmin -u root -p’oldpassword’ password newpass
For example, If the old password is abc, you can set the new password to 123456, enter:
Note: 123456 password is used for demonstration purpose only. You must select a strong password. It is an important protection to help you have safer MySQL database transactions.
- No ads and tracking
- In-depth guides for developers and sysadmins at Opensourceflare✨
- Join my Patreon to support independent content creators and start reading latest guides:
- How to set up Redis sentinel cluster on Ubuntu or Debian Linux
- How To Set Up SSH Keys With YubiKey as two-factor authentication (U2F/FIDO2)
- How to set up Mariadb Galera cluster on Ubuntu or Debian Linux
- A podman tutorial for beginners – part I (run Linux containers without Docker and in daemonless mode)
- How to protect Linux against rogue USB devices using USBGuard
Join Patreon ➔
Sample live session from my home server using mysqladmin
Fig.01: mysqladmin command in action
How do I verify that the new password is working or not?
Use the following mysql command:
mysql -u root -p’123456′ db-name-here
mysql -u root -p’123456′ -e ‘show databases;’
A note about changing MySQL password for other users
To change a normal user password you need to type the following command. In this example, change the password for nixcraft mysql user:
$ mysqladmin -u nixcraft -p’old-password’ password new-password
Method #2 : Changing MySQL root user password using the mysql command
This is an another method. MySQL stores username and passwords in user table inside MySQL database. You can directly update or change the password using the following method for user called nixcraft:
Login to mysql server, type the following command at shell prompt:
Use mysql database (type command at mysql> prompt):
Change password for user nixcraft, enter:
Finally, reload the privileges:
Sample live session from my home server
Fig.02: Changing mysql password for nixcraft user using sql commands.
See also:
🐧 Get the latest tutorials on Linux, Open Source & DevOps via
Category | List of Unix and Linux commands |
---|---|
Documentation | help • mandb • man • pinfo |
Disk space analyzers | df • duf • ncdu • pydf |
File Management | cat • cp • less • mkdir • more • tree |
Firewall | Alpine Awall • CentOS 8 • OpenSUSE • RHEL 8 • Ubuntu 16.04 • Ubuntu 18.04 • Ubuntu 20.04 |
Linux Desktop Apps | Skype • Spotify • VLC 3 |
Modern utilities | bat • exa |
Network Utilities | NetHogs • dig • host • ip • nmap |
OpenVPN | CentOS 7 • CentOS 8 • Debian 10 • Debian 8/9 • Ubuntu 18.04 • Ubuntu 20.04 |
Package Manager | apk • apt |
Processes Management | bg • chroot • cron • disown • fg • glances • gtop • jobs • killall • kill • pidof • pstree • pwdx • time • vtop |
Searching | ag • grep • whereis • which |
Shell builtins | compgen • echo • printf |
Text processing | cut • rev |
User Information | groups • id • lastcomm • last • lid/libuser-lid • logname • members • users • whoami • who • w |
WireGuard VPN | Alpine • CentOS 8 • Debian 10 • Firewall • Ubuntu 20.04 |
Comments on this entry are closed.
I got an error trying to use your method to change the root password using mysqladmin. I did some checking and found that the following method worked.
mysql> mysqladmin -u molly -p password NEWPASSWORD
(replacing NEWPASSWORD with the desired password, you will be prompted to enter the current password)
Which Operating System you used….
This site is a mess . now i can’t access to mysql *@*&#*&@)(***@)( you .
Lucas, you’re an idiot
This was extremely helpful. its a simple query really… Just needed the correct syntax. Thanks administrator.
This is old, but someone might see it. Don’t forget to put the single quotes around your password.
Really good post:
i hacked my root by using that type + batch file
Because i used special carectors for my password
Thanks again 😉
I am using the latest MySQL, the codes above didn;t work for me, please if you have the correct code to use. I want to change the root password to null. Just like it came.
mysql>SET PASSWORD FOR ‘root’@’localhost’ = PASSWORD(‘secret_password’);
Al, thx. That worked fine for mysql. However when I try to access mysqladmin
app now, I get a strange error.
“The additional features for working with linked tables have been deactivated.”
anyone have an idea for a fix?
Hello, I need help creating a password. I don’t know where I am supposed to enter the SET PASSWORD command.
computers can be sucha pain.
Yessssss… same for me…
It will not work.
I use WAMPSERVER 2.0
I get following error in Mysql:
ERROR 1064 (42000): You have an error in you SQL syntax; check the manual that corresponds to your MySql server version for the right syntax to use near ‘$ mysql -u root -p
mysql> use mysql
mysql> update user set password=PASSWORD(“NE’ at line 1
I’m using wamp server 2.1. Click on your wamp icon. mouse hover on Mysql
select console then type in Al’s suggestion. It worked fine for me.
you may have to refresh your page or clear cookies before you see the change.
I know I had too.
oh yeah, if it asks you for a password and you haven’t set one yet, just press
the enter key.
i want to set configure my mysql to set a new password i typed set password and the reply is this ERROR 1064 (42000): You have an error in you SQL syntax; check the manual that corresponds to your MySql server version for the right syntax to use near ‘$ mysql -u root -p
mysql> use mysql
mysql> update user set password=PASSWORD(“NE’ at line 1
This is a SQL statement.
SQL statements only use single quotes, one at a time.
try:
mysql
use mysql
update user root set password=PASSWORD(‘new’);
\q
this should work a lot better 😉
Are you stupid 😉
The mysql -u root -p doesn’t need to be entered in the mysql console. It’s the command to open the mysql console on linux systems.
The information on your website has helped me. Thanks.
Best Wishes,
K.Ramanathan
Thank you very much, this information was usefull!
If I forgot my mysql password? how is it going?, because there is a step that need an old mysql password.
ya I lost my Brain also 🙂
Go here to recover mysql password.
Worked like a charm, thnx.
thank you so much. i really needed this. ^^
mysqladmin -u root -p password “newPassword”
To update mysql password for root, the command that works for me is:
mysqladmin -u root -poldpass password newpass
mysqladmin -u root -p password ”
this will remove your password
Careful not to copy paste this. Use two single quotes instead of what you’d get if you copy/pasted this line.
mysqladmin -u root -p password [singlequote][singlequote]
Thanks Daniel. After persistently receive Access denied, this finally worked 🙂
mysqladmin -u root -p password
I found this quite frustrating. Not an ideal post about how to change the root pwd. Hate it.
Have been coming here for years to cut and paste that syntax
mysqladmin -u root password NEWPASSWORD
works great, guys the “NEWPASSWORD” is where you put the new password
it is lazier for me to come here to grab it than learn it myself, i
There are people out there that should not be using computers, as yesh, bob & brendon.
Thanks for sharing this very useful info.
HI! It worked for me changing password this way, but when I trying to flush privileges it says : ERROR 1146 (42S02): Table ‘mysql.servers’ doesn’t exist.
Whats wrong.
I was playing with WAMP tool. By default it had root password as empty. I wanted to provide a new password and not just leave it empty.
By this I will be giving simple steps which I learnt, where in one can make necessary changes for both mysql server and mysql client. Hopefully this will work perfect with any standalone mysql server and mysql client application. I hope this may save someones precious time.
WAMP Settings for MySQL
———————————-
By default WAMP does not set the mysql root password.
So phpmyadmin connects to internal mysqlServer with default username : root and empty[NO] password
If we want to have some form of secure database then root password should not be left empty.
How to provide the password so that mysql client connects to the server with some password?
The following tries to simplify the approach in WAMP Mysql setup.
Mysql Server End Changes for new Password
————————————————————–
Change the mysql server password as follows :
To setup root password for first time:
mysqladmin -u root password “NEWPASSWORD”
C:\wamp\bin\mysql\mysql5.1.30\bin> mysqladmin -u root password «root»
If password already exist and you are aware of it and want to change it then
1. Thru mysqladmin technique :
mysqladmin -u root -p password “MYNEWPASSWORD”
Enter password: OLDPASSWORD
C:\wamp\bin\mysql\mysql5.1.30\bin>mysqladmin -u root -p password “vinod”
Enter password: root
2. Alternatively, [Optional Step]
C:\wamp\bin\mysql\mysql5.1.30\bin>mysql -u root -p
Enter password: root [OLD EXISTING ROOT PASSWORD]
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 8
Server version: 5.1.30-community-log MySQL Community Server (GPL)
Type ‘help;’ or ‘\h’ for help. Type ‘\c’ to clear the buffer.
mysql> use mysql
Database changed
mysql> update user set password=PASSWORD(«vinod») where User=’root’;
Query OK, 1 row affected (0.00 sec)
Rows matched: 1 Changed: 1 Warnings: 0
This changes the root password.
C:\wamp\bin\mysql\mysql5.1.30\bin>mysql -u root -p
Enter password: vinod
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 5
Server version: 5.1.30-community-log MySQL Community Server (GPL)
Type ‘help;’ or ‘\h’ for help. Type ‘\c’ to clear the buffer.
Mysql Client End Changes for new Password
———————————————————
Change the mysql client password as follows :
Here phpmyadmin is a mysql client application which is connecting to mysql server.
Let us see what it requires to make changes to successfully connect with new password
1. Edit config.inc.php under C:\wamp\apps\phpmyadmin3.1.1\
Change
$cfg[‘Servers’][$i][‘password’] = »;
to
$cfg[‘Servers’][$i][‘password’] = ‘vinod’;
Thats it restart mysql service and http://localhost/phpmyadmin/ will let u login
Thanks for sharing Windows specific information.
Источник