Mariadb reset root password windows

Если у вас Linux, то смотрите статью «Как сбросить пароль root для MySQL или MariaDB».

Пароль пользователя root спрашивается во время установки СУБД. Если установка делалась вручную, то есть без инстолятора, как это описано, например, в этой статье, то пароль может быть не установлен вовсе.

Если вы используете какие-то готовые сборки, которые включают в себя MySQL/MariaDB, то обратитесь за паролем на официальные сайты этих сборок. Также попробуйте такие учётные данные:

  • Пользователь: root
  • Пароль: root

Если вы действительно забыли пароль MySQL/MariaDB и вам нужно сбросить пароль root в MySQL на Windows, то данная статья расскажет, как это сделать.

Шаг 1 — Определяем версию системы управления базой данных

Найдите, в какой папке у вас расположен файл mysqld.exe. При установке по данной инструкции, этот файл расположен в папке C:\Server\bin\mysql-8.0\bin\.

Откройте командную строку. Нам понадобятся права администратора, поэтому делаем следующее: нажмите Win+x и там выберите Windows PowerShell (администратор):

Теперь перейдите в командной строке в директорию с файлом mysqld.exe, для этого используйте команду вида:

cd путь\до\папки

Например, у меня это папка C:\Server\bin\mysql-8.0\bin\, тогда команда такая:

cd C:\Server\bin\mysql-8.0\bin\

Нужно определить версию MySQL/MariaDB, для этого выполните команду:

.\mysql --version

Пример вывода:

C:\Server\bin\mysql-8.0\bin\mysqld.exe Ver 8.0.19 for Win64 on x86_64 (MySQL Community Server - GPL)

Шаг 2 — Остановка сервера базы данных

Для изменения пароля root вы должны заранее отключить сервер базы данных. Для MySQL и MariaDB вы можете сделать это командой:

net stop mysql

После того, как сервер остановлен, вы вручную получите к нему доступ для сброса пароля рута.

Шаг 3 — Перезапуск сервера базы данных без проверки разрешений

Если вы запускаете MySQL и MariaDB без загрузки информации о привилегиях пользователя, она позволит вам без ввода пароля получить доступ к командной строке базы данных с привилегиями рута. Это позволит вам получить доступ к базе данных без знания парольной фразы. Чтобы это сделать, вам нужно не дать базе данных загрузить таблицы привилегий, которые содержат информацию о привилегиях пользователя. Поскольку это несёт риск безопасности, вы также должны избежать сетевой активности, чтобы не допустить подключения других клиентов.

Запустите базу данных без загрузки таблиц привилегий и без доступа к сети:

.\mysqld --skip-grant-tables --skip-networking --shared-memory

Программа НЕ должна завершить работу, то есть теперь в это окно командной строки ничего нельзя ввести.

Шаг 4 — Смена пароля рута

Теперь вы можете подключиться к базе данных как пользователь рут, у которого не спросят пароль.

Открываем новое окно командной строки, можно без прав администратора.

Опять переходим в нужную папку

cd C:\Server\bin\mysql-8.0\bin\

И подключаемся к серверу MySQL/MariaDB

.\mysql -u root

Вы сразу же увидите приглашение оболочки базы данных. Приглашение командной строки MySQL:

Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 8
Server version: 8.0.19 MySQL Community Server - GPL

Copyright (c) 2000, 2020, Oracle and/or its affiliates. All rights reserved.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

Теперь, когда у вас имеется рут доступ, вы можете изменить пароль рута.

Простым способом смены пароля рута для современных версий MySQL является использование запроса ALTER USER. Тем не менее эта команда не будет работать прямо сейчас, поскольку таблицы привилегий не загружены. Давайте скажем серверу баз данных перегрузить таблицы привилегий введя команду:

FLUSH PRIVILEGES;

Теперь действительно мы можем поменять пароль рута.

Для MySQL 5.7.6 и новее, а также для MariaDB 10.1.20 и новее используйте следующую команду:

ALTER USER 'root'@'localhost' IDENTIFIED BY 'новый_пароль';

Для MySQL 5.7.5 и старее, а также для MariaDB 10.1.20 и старее используйте:

SET PASSWORD FOR 'root'@'localhost' = PASSWORD('новый_пароль');

Не забудьте поменять новый_пароль на выбранный вами новый пароль.

Примечание: если команда ALTER USER не работает, то это обычно является признаком более серьёзной проблемы. Тем не менее вместо этой вы можете попробовать UPDATE … SET для сброса root пароля:

UPDATE mysql.user SET authentication_string = PASSWORD('новый_пароль') WHERE User = 'root' AND Host = 'localhost';

После этого не забудьте перегрузить таблицы привилегий:

FLUSH PRIVILEGES;

В любом случае вы должны видеть подтверждение, что команда успешно выполнена. Вывод:

Query OK, 0 rows affected (0.02 sec)

Выходим из сессии:

exit;

Пароль изменён, вы можете остановить запущенный вручную экземпляр сервера базы данных и перезапустить его как это было раньше.

Шаг 5 — Обычный перезапуск сервера базы данных

Для начала, остановите экземпляр сервера базы данных, который вы запустили вручную на Шаге 3. Для этого перейдите в окно с запущенной mysqld и нажмите Ctrl+c.

Затем перезапустите сервис обычным образом:

net start mysql

Теперь вы можете подтвердить, что новый пароль работает, запустите:

.\mysql -u root -p

Эта команда должна вызвать приглашение в который нужно ввести новый пароль. Введите его, вы должны получить доступ к интерфейсу командной строки базы данных, как это обычно и происходит.

Заключение

Теперь вы восстановили административный доступ к серверу MySQL или MariaDB. Убедитесь, что новый пароль рута, который вы выбрали, безопасный и храните его в надёжном месте.

Ошибка «—shared-memory, or —named-pipe should be configured on NT OS»

Если при запуске mysqld вы столкнулись со следующей ошибкой:

[ERROR] [MY-010131] [Server] TCP/IP, --shared-memory, or --named-pipe should be configured on NT OS

то вам необходимо к команде запуска mysqld добавить флаг —shared-memory.

Связанные статьи:

  • MariaDB для Windows (100%)
  • Как обновить MySQL (100%)
  • Как обновить MariaDB в Windows (100%)
  • Как сделать резервную копию баз данных MySQL (MariaDB) в Windows без phpMyAdmin (100%)
  • Как в phpMyAdmin поменять настройки экспорта по умолчанию (100%)
  • Как тестировать отправку писем в PHP на Windows (RANDOM — 50%)

How to reset password in MariaDB? I use Windows and NOT Linux. Anyone who knows how to reset my MySQL MariaDB password? I tried to search on Google but did not help.

Akash Mahapatra's user avatar

asked Apr 25, 2014 at 9:06

user3572244's user avatar

0

As this is top result in Google here’s a quick way to change the password:

  1. Stop the DB server

  2. create a text file containing your new password:

    ALTER USER 'root'@'localhost' IDENTIFIED BY 'DontForgetMeAgain';
    
  3. Run this command (don’t forget to replace the path to file):

    mysqld --init-file=C:\\path\\to\\file.txt
    

And we’re done

answered Jun 6, 2020 at 15:57

Tom's user avatar

TomTom

2442 silver badges4 bronze badges

3

I bumped into the same problem. I lost the root password for a test server on a windows development machine.
Following the Linux step:

After

net stop mysql 

Try invoking mysqld with

mysqld --skip-grant-tables

mysqld will only exit with a short message

[Note] mysqld.exe <...5.5.48.MariaDB> starting as process <pid> ...

then it quits. However I tried to launch mysqld directly, there is no mysqld.exe process. The service start command might have some argument combination that enabled mysqld to run. Tried to pass the settings through a configuration file and it works.

put

skip-grant-tables=TRUE

into MariaDB 5.5\data\my.ini
Restart mysqld, by

net stop mysql && net start mysql

then being able to login as root.

Don’t forget to remove the inserted line and restart mysqld again.

Akash Mahapatra's user avatar

answered Sep 25, 2016 at 5:38

Ben's user avatar

BenBen

1,1431 gold badge15 silver badges30 bronze badges

Using skip-grant-tables led Maria Db to complain when changing a password even if logged in as root.
I had to do a little modification on Tom’s answer in the content of the file to make it work for me:

After stopping the DBServer i created a file with this content:

SET PASSWORD FOR 'root'@'localhost' = PASSWORD('mynewpassword');
FLUSH PRIVILEGES;

then I run:

C:\Program Files\MariaDB 10.1\bin>mysqld --init-file=C:\\path\\to\\file.txt

I then managed to log in

answered Apr 12, 2021 at 14:54

david-ao's user avatar

david-aodavid-ao

3,0206 silver badges13 bronze badges

In this MariaDB tutorial, we will learn about the MariaDB reset root password and cover the following topics.

  • MariaDB reset root password windows
  • MariaDB reset root password ubuntu
  • MariaDB reset root password mac
  • MariaDB reset root password docker
  • MariaDB reset root password Linux
  • MariaDB reset root password xampp
  • MariaDB reset root password Debian 9
  • MariaDB 10.3 reset root password

In this section, we will learn how to reset the password of MariaDB. Sometimes, we forget the password, so will recover the password of MariaDB that running on a Windows machine. To recover the password we must have access to that MariaDB server.

Follow the below steps to reset the password.

Firstly, check the version of the MariaDB server by opening the command line on windows and typing the below command in that command line.

mysql --version
MariaDB reset root password windows checking version
MariaDB reset root password windows checking version

If unable to run this command in the command line, then go to the C:\Program Files\MariaDB 10.6 folder of MariaDB where it is installed on your windows machine and from the folder we can see it is MariaDB 10.6 version.

Secondly, stop the database server by opening the command line as the administrator, typing the below code.

net stop MairaDB

If the MariaDB version is 10.4 or a later version then run the above code, for the MariaDB version before 10.4 run the below code to stop the database server.

net stop MySQL

Here we are using the MariaDB 10.6 version so we will run the command net stop MariaDB.

MariaDB reset root password windows stop server
MariaDB reset root password windows stop server

Thirdly, restart the MariaDB server without loading the grant tables like user and db, these grant tables contain information about the user privileges that who can log in and has access to which database.

When the MariaDB server restarts without user privileges information or grant tables, then any user can log in to MariaDB using the command line without a password as the root user. Additionally, we will also skip the network while restarting MariaDB so that other users can’t connect to this server.

Go to the bin folder of MariaDB (C:\Program Files\MariaDB 10.6\bin) where it is installed. open the command line and type the below code to restart the MariaDB server without grant tables.

cd C:\Program Files\MariaDB 10.6\bin

./mysqld --skip-grant-tables --skip-networking --shared-memory
MariaDB reset root password windows restart server with grant tables
MariaDB reset root password windows restart server with grant tables

Fourthly, let’s reset the password of MariaDB, open the command line, and type the below code to log in as a root user without a password.

mysql -u root

After running the above code in the command line, we have logged into MariaDB as a root user that we can see in the below output.

MariaDB reset root password windows log in
MariaDB reset root password windows log in

Before resetting the password, load the grant tables that contain information about user privileges. Run the below code to reload the grant tables in MariaDB prompt.

FLUSH PRIVILEGES;

Reset the password using the below code.

ALTER USER 'root'@'localhost' IDENTIFIED BY 'new_user_password';

If the MariaDB version is 10.1.20 or later then use the above code, otherwise use the below code for MariaDB version 10.1.20.

SET PASSWORD FOR 'root'@'localhost' = PASSWORD('new_user_password');

Again reload the grant tables using the below code.

FLUSH PRIVILEGES;

After running the above code, it shows the output as Query OK, 0 rows affected (0.011 sec).

Exit from the MariaDB prompt or session.

exit
MariaDB reset root password windows
MariaDB reset root password windows

We have reset the password of MariaDB manually. Now restart the MariaDB server normally by opening the command line as administrator and typing the below code in that command line.

net start MariaDB
MariaDB reset root password windows tutorial
MariaDB reset root password windows tutorial

Login with a new password in MariaDB by typing the below command in the command line.

mysql -u root -p

If the above command asks for a password then enter the new password that we reset for the root user in the above steps.

MariaDB reset root password windows reset login
MariaDB reset root password windows reset login

From the output, we can see that we have successfully reset the password of MariaDB.

Also, check: MariaDB Backup Database

MariaDB Reset Root Password Ubuntu

To reset the password of MariaDB on Ubuntu some of the commands are the same for MariaDB that we have used in the above sub-section. Follow the below steps to reset the password of MariaDB on Ubuntu.

First, check the version of MariaDB using by opening the terminal and typing the below code in that terminal.

mysql --version
MariaDB reset root password Ubuntu check version
MariaDB reset root password Ubuntu check version

Stop the MariaDB server, so we can reset the password of MariaDB manually. Use the below code to stop the database server.

sudo systemctl stop mariadb

After stopping the MariaDB server, run the below code to restart the MariaDB server without grant tables. When the MariaDB server restarts without user privileges information or grant tables, then any user can log in to MariaDB using the command line without a password as the root user.

Additionally, we will also skip the network while restarting MariaDB so that other users can’t connect to this server.

sudo mysqld_safe --skip-grant-tables --skip-networking &
MariaDB reset root password Ubuntu check restart without grant tables
MariaDB reset root password Ubuntu check restart without grant tables

Login into the MariaDB prompt without entering the password by typing the below code in the same terminal.

mysql -u root

Now we can reset the password of MariaDB because we logged in as a root user so we have full access to the database.

Before resetting the password, reload the grant table using the below code.

FLUSH PRIVILEGES;

Reset the password using the below code.

ALTER USER 'root'@'localhost' IDENTIFIED BY 'new_user_password';

If the MariaDB version is 10.1.20 or later then use the above code, otherwise use the below code for MariaDB version 10.1.20.

SET PASSWORD FOR 'root'@'localhost' = PASSWORD('new_user_password');

Again reload the grant tables using the below code.

FLUSH PRIVILEGES;

After running the above code, it shows the output as Query OK, 0 rows affected (0.001 sec).

Exit from the MariaDB prompt or session.

exit
MariaDB reset root password Ubuntu
MariaDB reset root password Ubuntu

We have reset the password of the MariaDB server manually, After this, restart the MariaDB server in normal mode by restarting the Ubuntu machine. Run the below code to check the status of the MariaDB server.

systemctl status mariadb

Then login into the MariaDB server with a new password.

mysql -u root -p
MariaDB reset root password Ubuntu login
MariaDB reset root password Ubuntu login

From the output, we can see that we have successfully login into MariaDB with a new password.

Read: MariaDB Enable Remote Access

MariaDB Reset Root Password Mac

To reset the root password in Mac OS, follow the steps provided in the above subsection “MariaDB reset root password Ubuntu”.

MariaDB Reset Root Password Docker

To reset the root password of MariaDB follow the below steps.

Open the docker-compose file for MariaDB and add the line command: --skip-grant-tables at the end of the file as given in the below output.

# Use root/example as user/password credentials
version: '3.1'

services:

  db:
    image: mariadb
    restart: always
    environment:
      MYSQL_ROOT_PASSWORD: example
    ports:
      - 8080:8080
    command: --skip-grant-tables
MariaDB reset root password docker compose file
MariaDB reset root password docker-compose file

After adding the line, restart the container MariaDB using the below code in the directory where the above compose file exists.

docker-compose down -- to stop the running container

Then start the container.

docker-compose up -- to start the container with new setting 

Access the bash shell of the MariaDB container by clicking on the button CLI in docker application.

Login into MariaDB as root user using the below code.

mysql -u root

Before resetting the password, reload the grant table using the below code.

FLUSH PRIVILEGES;

Reset the password using the below code.

ALTER USER 'root'@'localhost' IDENTIFIED BY 'new_user_password';

If the MariaDB version is 10.1.20 or later then use the above code, otherwise use the below code for MariaDB version 10.1.20.

SET PASSWORD FOR 'root'@'localhost' = PASSWORD('new_user_password');

Again reload the grant tables using the below code.

FLUSH PRIVILEGES;

After running the above code, it shows the output as Query OK, 0 rows affected (0.011 sec).

Exit from the MariaDB prompt or session.

exit
MariaDB reset root password docker
MariaDB reset root password docker

After performing the above steps, exit the bash shell of the MariaDB container, stop the MariaDB container and open the docker-compose file, remove the line command: --skip-grant-tables from the file and save the file. Then restart the container again with changes setting using the below code.

sudo nano docker-compose file -- opening the compose file

Then start the container.

docker-compose up -- to start the container with new setting 

Again access the bash shell of the MariaDB container using the below code or use the docker desktop application to open the base shell of that container.

docker exec -it mariadbtips-db-1 bash

Login into MariaDB as root user with a new password using the below code.

mysql -u root -p
MariaDB reset root password docker login
MariaDB reset root password docker login

Read: MariaDB Check If Rows Exists

MariaDB Reset Root Password Linux

To reset the root password of MariaDB in Linux, follow the steps of the tutorial “MariaDB reset root password Ubuntu” because all Linux-based operating systems follow the same steps to reset the password of MariaDB.

MariaDB Reset Root Password xampp

The XAMPP is a cross-platform web server developed by Apache. So here we will reset the password of MariaDB using XAMPP shell and for that follow the below steps.

Open the XAMPP control panel on your system and click on the button Conifg of MySQL, then option appears as my.ini and click on my.ini option to open the file as shown in the below picture.

MariaDB reset root password xampp control panel
MariaDB reset root password xampp control panel

After opening the file, add the given line below the line [mysqld] of file my.ini and save the file.

skip-grant-tables
MariaDB reset root password xampp configuration
MariaDB reset root password xampp configuration

Then come back to the XAMPP control panel, stop and start the MySQL server to take effect on changes that we made. After this, we will be able to log into the database without a password as the root user.

Click on the button Shell to open the shell, check the version, and login into the database without a password.

MariaDB reset root password xampp configuration login
MariaDB reset root password xampp configuration login

Before resetting the password, reload the grant table using the below code.

FLUSH PRIVILEGES;

Reset the password using the below code.

ALTER USER 'root'@'localhost' IDENTIFIED BY 'new_user_password';

If the MariaDB version is 10.1.20 or later then use the above code, otherwise use the below code for MariaDB version 10.1.20.

SET PASSWORD FOR 'root'@'localhost' = PASSWORD('new_user_password');

Again reload the grant tables using the below code.

FLUSH PRIVILEGES;

After running the above code, it shows the output as Query OK, 0 rows affected (0.000 sec).

Exit from the MariaDB prompt or session.

exit
MariaDB reset root password xampp
MariaDB reset root password xampp

Then again open the file my.ini and remove the line skip-grant-tables and restart the MySQL server.

Login with a new password that we set for the root user in the above steps.

mysql -u root -p
MariaDB reset root password xampp login after reset
MariaDB reset root password xampp login after reset

Now we have successfully logged into the database with a reset password.

Read: MariaDB Truncate Table + Examples

MariaDB reset root password Debian 9

The same steps are used to reset the password of MariaDB in Debian 9 as we have used the above sub-section “MariaDB reset root password Ubuntu”.

Read: MariaDB Rename View

MariaDB 10.3 Reset Root Password

So in this section, we will reset the root password of MariaDB 10.3 and follow the below steps.

Firstly, check the version of the MariaDB server by opening the command line on windows and typing the below command in that command line.

mysql --version
MariaDB reset root password windows checking version MariaDB 10.3
MariaDB reset root password windows checking version MariaDB 10.3

If unable to run this command in the command line, then go to the C:\Program Files\MariaDB 10.3 folder of MariaDB where it is installed on your windows machine and from the folder we can see it is MariaDB 10.3 version.

Secondly, stop the database server by opening the command line as the administrator, typing the below code.

net stop MairaDB

If the MariaDB version is 10.4 or a later version then run the above code, for the MariaDB version before 10.4 run the below code to stop the database server.

net stop MySQL

Here we are using the MariaDB 10.6 version so we will run the command net stop MariaDB.

MariaDB reset root password windows stop server
MariaDB reset root password windows stop server

Thirdly, restart the MariaDB server without loading the grant tables like user and db, these grant tables contain information about the user privileges that who can log in and has access to which database.

When the MariaDB server restarts without user privileges information or grant tables, then any user can log in to MariaDB using the command line without a password as the root user. Additionally, we will also skip the network while restarting MariaDB so that other users can’t connect to this server.

Go to the bin folder of MariaDB (C:\Program Files\MariaDB 10.6\bin) where it is installed. open the command line and type the below code to restart the MariaDB server without grant tables.

cd C:\Program Files\MariaDB 10.6\bin

./mysqld --skip-grant-tables --skip-networking --shared-memory
MariaDB reset root password windows restart server with grant tables
MariaDB reset root password windows restart server with grant tables

Fourthly, let’s reset the password of MariaDB, open the command line, and type the below code to log in as a root user without a password.

mysql -u root

After running the above code in the command line, we have logged into MariaDB as a root user that we can see in the below output.

MariaDB reset root password windows log in
MariaDB reset root password windows log in

Before resetting the password, load the grant tables that contain information about user privileges. Run the below code to reload the grant tables in MariaDB prompt.

FLUSH PRIVILEGES;

Reset the password using the below code.

ALTER USER 'root'@'localhost' IDENTIFIED BY 'new_user_password';

If the MariaDB version is 10.1.20 or later then use the above code, otherwise use the below code for MariaDB version 10.1.20.

SET PASSWORD FOR 'root'@'localhost' = PASSWORD('new_user_password');

Again reload the grant tables using the below code.

FLUSH PRIVILEGES;

After running the above code, it shows the output as Query OK, 0 rows affected (0.011 sec).

Exit from the MariaDB prompt or session.

exit
MariaDB reset root password windows
MariaDB reset root password windows

We have reset the password of MariaDB manually. Now restart the MariaDB server normally by opening the command line as administrator and typing the below code in that command line.

net start MariaDB
MariaDB reset root password windows tutorial
MariaDB reset root password windows tutorial

Login with a new password in MariaDB by typing the below command in the command line.

mysql -u root -p

If the above command asks for a password then enter the new password that we reset for the root user in the above steps.

MariaDB reset root password windows reset login
MariaDB reset root password windows reset login

From the output, we can see that we have successfully reset the password of MariaDB.

You may also like to read the following MariaDB tutorials.

  • MariaDB Left Join
  • MariaDB Rename Column
  • MariaDB Truncate Table
  • MariaDB Union Operator
  • MariaDB Case Statement
  • MariaDB Variables Tutorial
  • MariaDB Temporary Table

So, in this tutorial, we have learned about the “MariaDB reset root password“, learned how to reset the MariaDB on different systems, and covered the following topics.

  • MariaDB reset root password windows
  • MariaDB reset root password ubuntu
  • MariaDB reset root password mac
  • MariaDB reset root password docker
  • MariaDB reset root password Linux
  • MariaDB reset root password xampp
  • MariaDB reset root password Debian 9
  • MariaDB 10.3 reset root password

Bijay

I am Bijay having more than 15 years of experience in the Software Industry. During this time, I have worked on MariaDB and used it in a lot of projects. Most of our readers are from the United States, Canada, United Kingdom, Australia, New Zealand, etc.

Want to learn MariaDB? Check out all the articles and tutorials that I wrote on MariaDB. Also, I am a Microsoft MVP.

  • Главная

  • Инструкции

  • MySQL

  • Как сбросить пароль root MySQL: пошаговая инструкция

Получение доступа к базам данных является важной задачей при управлении серверами и обслуживании веб-приложений. Одной из самых распространенных и мощных систем управления базами данных (СУБД) является MySQL. Как администратор базы данных, вы храните важную информацию, и пароль root MySQL играет решающую роль в обеспечении безопасности и целостности данных.

Время от времени может возникнуть ситуация, когда вы теряете или забываете пароль root MySQL. Это может произойти по разным причинам, от непредвиденных обстоятельств до изменения команды или просто человеческой ошибки. В таких случаях критически важно знать, как сбросить пароль root и восстановить доступ к базе данных.

В данной статье мы представим вам методы и инструменты, которые помогут сбросить пароль root в MySQL и восстановить полный контроль над вашей базой данных. Мы охватим различные подходы, начиная от использования официальных инструментов MySQL, таких как mysqladmin и mysqld_safe, до редактирования файлов конфигурации и внесения изменений в систему.

Стоит отметить, что восстановление доступа к паролю root MySQL является сложной задачей и требует определенных знаний и навыков. Поэтому рекомендуем внимательно ознакомиться с инструкциями, чтобы избежать возможных проблем или потери данных.

Мы также обсудим важные меры предосторожности, которые помогут вам обеспечить безопасность вашей базы данных и предотвратить потерю пароля root в будущем. Это включает в себя использование надежных паролей, ограничение доступа к базе данных только необходимым пользователям и регулярное резервное копирование данных для минимизации рисков.

Итак, если вы столкнулись с проблемой утери пароля root в MySQL, не волнуйтесь. В статье ниже вы найдете подробные инструкции и рекомендации, которые помогут вам восстановить доступ и вернуться к управлению вашей базой данных MySQL.

MySQL не использует PAM и пароль от SSH не подойдёт. Пароль root задаётся в процессе установки сервера баз данных, на этапе формирования таблиц привилегий.

Если после попытки входа вместо приветствия база данных выдаёт ошибку ERROR 1045: Access denied for user 'root'@'localhost', значит нужно сбросить root-пароль.

Чтобы в MySQL 8 сбросить пароль root, необходимо пройти несложную процедуру. Она одинаково подходит как для традиционного MySQL, так и для MariaDB. Они полностью совместимы и имеют одинаковые команды.

В Ubuntu сбросить пароль root для MySQL можно такими же методами, как и в Debian, конкретной привязки к ОС нет. Небольшое отличие возможно для CentOS 7, это мы отметим ниже в соответствующем пункте.

Как в MySQL сбросить пароль root методом skip-grant-tables

Достаточно распространённый способ, ввиду его простоты. Приводим пошаговый план этой операции:

Шаг 1

Остановим службу базы данных:

service mysqld stop

Шаг 2

Запускаем службу без таблиц привилегий:

mysqld --skip-grant-tables&

Амперсанд в конце позволяет запустить службу в фоне и она не занимает отдельное окно терминала.

Шаг 3

Подключаемся к серверу. Так как таблицы привилегий не подключены, соответственно пароль вводить нет необходимости:

mysql -u root

Каждая команда к базе данных обязательно должна заканчиваться точкой с запятой. Если запрос не отбит, MySQL будет ожидать продолжения команды. В новую строку можно просто указать точку с запятой, если она была упущена.

Шаг 4

Подключаем таблицы привилегий:

FLUSH PRIVILEGES;

В ответ получаем: Query OK, 0 rows affected.

Шаг 5

Установим новый пароль суперпользователя root:

ALTER USER 'root'@'localhost' IDENTIFIED BY 'ПАРОЛЬ';

Если этот запрос не сработал, попробуйте:

UPDATE `mysql`.`user` SET `password`=password('ПАРОЛЬ') WHERE `user`='root';

Или:

SET PASSWORD FOR 'root'@'localhost' = PASSWORD('ПАРОЛЬ');

На CentOS 7 сбросить пароль MySQL root можно, выполнив команду:

UPDATE `mysql`.`user` SET ` authentication_string`=password('ПАРОЛЬ') WHERE `user`='root';

Об успешности выполнения можно судить по ответу Query OK, 0 rows affected. Пароль может быть даже пустым значением, но в таком случае будет потеряна возможность подключения к серверу любыми другими способами, кроме командной строки. Пароль изменяется сразу после ввода команды. Проверить можно, например, подключившись через phpMyAdmin, если не было передано пустое значение.

Шаг 6

Выход из mysql:

quit;

В ответ получим Bye, вернётся обычный терминал.

Шаг 7

Запускаем сервер баз данных в штатном режиме:

service mysqld start

Как в MySQL сбросить пароль root на ОС Windows

Сброс пароля суперпользователя MySQL под ОС Windows схож с процедурой сброса root-пароля СУБД для Linux-систем. Некоторые отличия могут быть только в процессе поиска и запуска службы самой базы данных. Из-за разных названий служб MySQL и MariaDB нет привязки к названию «mysql», и иногда необходимо указывать конкретное название службы. Рассмотрим пошагово сброс пароля суперпользователя базы данных для ОС Windows.

Шаг 1

Открываем интерпретатор команд в режиме Администратора. В этом случае есть разница, какая база данных установлена, в Windows службы имеют различные названия. Проверяем, какая установлена:

Для MySQL:

sc qc "mysql"

Для MariaDB:

sc qc "mariadb"

В случае, если служба отсутствует, будет показано сообщение «Указанная служба не установлена». При успешном выполнении будет выведена основная служебная информация.

Шаг 2

Если не установлена переменная %PATH%, необходимо перейти в папку с исполняемым файлом службы базы данных, путь можно определить по ответу sc qc в «Имя_двоичного_файла». В нашем случае это С:\localhost\mariadb\bin\.

cd C:\localhost\mariadb\bin\

Если диск другой, то переходим на него, указав букву диска, например:

D:

Шаг 3

Остановим уже запущенную службу:

Для MySQL:

net stop mysql

Для MariaDB:

net stop mariadb

Шаг 4

Откроем окно дополнительного интерпретатора командой start. В отличие от Linux, в Windows амперсанд в конце команды не работает, а при запуске службы она не даст более вводить команды до окончания сессии (нажатии CTRL+C).

Шаг 5

Запуск сервера без привилегий (идентично для MySQL и MariaDB):

mysqld --skip-grant-tables

Шаг 6

Во втором окне вводим:

mysql -uroot -p

Вводим пустой пароль, видим стандартное приветствие. Теперь необходимо вводить команды для сервера баз данных.

Шаг 7

Для начала необходимо выполнить команду:

FLUSH PRIVILEGES;

Без этой начальной команды можно получить ошибку при смене пароля: «ERROR 1290: The MariaDB server is running with the —skip-grant-tables option so it cannot execute this statement». 

Шаг 8

Выполняем команду:

ALTER USER 'root'@'localhost' IDENTIFIED BY 'ПАРОЛЬ';

Примечание: если команда не сработала, попробуйте варианты из пятого шага инструкции для Linux-систем.

Закрываем окно интерпретатора с запущенной временной версией базы данных или нажимаем CTRL+C.

Шаг 9

Запускаем системную службу:

Для MySQL:

net start mysql

Для MariaDB:

net start mariadb

Заключение

Восстановление доступа к паролю root в MySQL является важным навыком для администраторов баз данных. В данной статье мы рассмотрели различные методы и инструменты, которые помогут вам сбросить пароль root и восстановить полный контроль над вашей базой данных.

В заключение, хочется подчеркнуть несколько ключевых моментов, касающихся безопасности баз данных.

  • Используйте сложные пароли, состоящие из комбинации букв, цифр и специальных символов, а также регулярно меняйте их. 
  • Ограничьте доступ к базе данных только необходимым пользователям, чтобы минимизировать риски несанкционированного доступа. 
  • Регулярно обновляйте систему MySQL, чтобы устранять известные уязвимости и получать последние исправления безопасности.
  • Регулярно создавайте резервные копии базы данных. Это ваша страховка в случае потери данных или сбоя системы. Разработайте стратегию резервного копирования, определите частоту и методы создания резервных копий, а также проверяйте их восстанавливаемость, чтобы быть уверенными в возможности восстановления данных.
  • Помните о важности обучения и саморазвития в области управления базами данных. Будьте в курсе последних тенденций, новых функций и инструментов MySQL. Воспользуйтесь обучающими ресурсами, участвуйте в семинарах и конференциях, а также общайтесь с опытными профессионалами в этой области. Постоянное обновление своих знаний и навыков поможет вам эффективно управлять базой данных и решать возникающие проблемы.

Восстановление пароля root в MySQL — это важная задача, требующая внимания и знаний. Однако с помощью изученных методов и рекомендаций, вы сможете справиться с этой задачей и вернуть полный контроль над вашей базой данных MySQL. Помните об обеспечении безопасности, создании резервных копий и постоянном обучении, и ваша работа с MySQL будет успешной и безопасной.

Reset the Root user password in MySQL or MariaDB on the Window platform

  1. Create an empty file with the name change password in C: drive or any other location.
C:\changepassword.txt

2. Edit the file and enter in the later command as follows and save the file:

ALTER USER 'root'@'localhost' IDENTIFIED BY 'NewPassword';

3. Open the services.msc and stop the MySQL service.

4. Right-click on MySQL80 services and get the path from where the service running and its default in the file location

"C:\Program Files\MySQL\MySQL Server 8.0\bin\mysqld.exe" --defaults-file="C:\ProgramData\MySQL\MySQL Server 8.0\my.ini" MySQL80

5. Open the cmd and run the command as follows to change the password:

cd "C:\Program Files\MySQL\MySQL Server 8.0\bin"
mysqld --init-file=C:\\changepassword.txt

6. If you have some default configuration then run as otherwise start the service and try to login with a new password; Start the service that already includes the default file. The following command is not needed to execute:

mysqld.exe --init-file=C:\\mysql-init.txt --defaults-file="C:\ProgramData\MySQL\MySQL Server 8.0\my.ini" MySQL80

  • Manually initiated crash windows 10
  • Maps что это за программа и нужна ли она на windows 10
  • Manli c media m cmi8738 6ch драйвер windows 10
  • Mariadb odbc driver for windows
  • Marc c windows 10 fix