Как сбросить пароль root для mysql или mariadb


Setting the password for the first time

Do note, throughout this article, I will refer to MySQL, with the idea that everything will work for both MySQL and MariaDB.

Typically, during the installation of MySQL and MariaDB, you are asked to set an initial password. If, for whatever reason that didn’t happen, you will need to set a password for the first time. To do that, open up a terminal window and issue the following command:

mysqladmin -u root password NEWPASSWORD

Where NEWPASSWORD is the password to be used. Now, when you log into MySQL, with the command mysql -u root -p, you will be prompted to enter the newly configured password.

An alternative method for setting the root password for the first time, one that also adds a bit of security to your MySQL database, is to use the mysql_secure_connection command. Not only will this command set the root user password, but it will allow you to remove anonymous users, disallow remote root login, and remove the test database. To use this command, simply type:


Answer the presented questions and your password will be set (as well as your database being a bit more secure).

SEE: Password management policy (Tech Pro Research)

Необходимые условия для настройки самостоятельной разблокировки учетной записи и сброса пароля с использованием MFAPrerequisites to set up self-service account unlock and password reset using MFA

В этом разделе предполагается, что вы скачали Microsoft Identity Manager 2016, службу синхронизации MIM, службу MIM и портал MIM и завершили его развертывание, включая следующие компоненты и службы:This section assumes that you have downloaded and completed the deployment of the Microsoft Identity Manager 2016 MIM Sync, MIM Service and MIM Portal components, including the following components and services:

  • Windows Server 2008 R2 или более поздней версии установлена на сервере Active Directory, включая доменные службы AD и контроллер домена с назначенным доменом (домен организации).A Windows Server 2008 R2 or later has been set up as an Active Directory server including AD Domain Services and Domain Controller with a designated domain (a “corporate” domain)

  • Групповая политика, определенная для блокирования учетных записейA Group Policy is defined for Account lockout

  • Служба синхронизации MIM 2016 установлена и запущена на сервере, присоединенном к домену AD.MIM 2016 Synchronization Service (Sync) is installed and running on a server that is domain-joined to the AD domain

  • Служба и портал MIM 2016, включающие портал регистрации SSPR и портал сброса SSPR, установлены и запущены на сервере (они могут быть размещены вместе со службой синхронизации).&MIM 2016 Service & Portal including the SSPR Registration Portal and the SSPR Reset Portal, are installed and running on a server (could be co-located with Sync)

  • Служба синхронизации MIM настроена для синхронизации удостоверений AD-MIM, в том числе:MIM Sync is configured for AD-MIM identity synchronization, including:

    • Настройка агента управления Active Directory (ADMA) для подключения к AD DS и возможности импорта данных удостоверения из службы Active Directory и экспорта в нее.Configuring the Active Directory Management Agent (ADMA) for connectivity to AD DS and capability to import identity data from and export it to Active Directory.

    • Настройка агента управления MIM (MIM MA) для подключения к базе данных службы FIM и возможности импорта данных удостоверения из базы данных FIM и экспорта их в нее.Configuring the MIM Management Agent (MIM MA) for connectivity to FIM Service DB and capability to import identity data from and export it to the FIM database.

    • Настройка правил синхронизации на портале MIM для синхронизации данных пользователей и выполнения действий на основе синхронизации в службе MIM.Configuring Synchronization Rules in the MIM Portal to allow user data synchronization and facilitate sync-based activities in the MIM Service.

  • Надстройки и расширения MIM 2016, в том числе встроенный клиент входа Windows SSPR, развернуты на сервере или отдельном клиентском компьютере.&MIM 2016 Add-ins & Extensions including the SSPR Windows Login integrated client is deployed on the server or on a separate client computer.

Для этого сценария требуются клиентские лицензии CAL MIM для пользователей, а также подписка на Azure MFA.This scenario requires you to have MIM CALs for your users as well as subscription for Azure MFA.

Additional attributes

In addition to the attributes that operate on all elements regardless of their type, password field inputs support the following attributes:

Attribute Description
The maximum length the value may be, in UTF-16 characters
The minimum length in characters that will be considered valid
A regular expression the value must match in order to be valid
An example value to display in the field when the field is empty
A Boolean attribute which, if present, indicates that the field’s contents should not be editable
The number of characters wide the input field should be

The maximum number of characters (as UTF-16 code units) the user can enter into the password field. This must be an integer value 0 or higher. If no is specified, or an invalid value is specified, the password field has no maximum length. This value must also be greater than or equal to the value of .

The input will fail constraint validation if the length of the text entered into the field is greater than UTF-16 code units long.

The minimum number of characters (as UTF-16 code units) the user can enter into the password entry field. This must be an non-negative integer value smaller than or equal to the value specified by . If no is specified, or an invalid value is specified, the password input has no minimum length.

The input will fail constraint validation if the length of the text entered into the field is fewer than UTF-16 code units long.

The attribute, when specified, is a regular expression that the input’s must match in order for the value to pass constraint validation. It must be a valid JavaScript regular expression, as used by the type, and as documented in our guide on regular expressions; the flag is specified when compiling the regular expression, so that the pattern is treated as a sequence of Unicode code points, instead of as ASCII. No forward slashes should be specified around the pattern text.

If the specified pattern is not specified or is invalid, no regular expression is applied and this attribute is ignored completely.

Tip: Use the attribute to specify text that most browsers will display as a tooltip to explain what the requirements are to match the pattern. You should also include other explanatory text nearby.

Use of a pattern is strongly recommended for password inputs, in order to help ensure that valid passwords using a wide assortment of character classes are selected and used by your users. With a pattern, you can mandate case rules, require the use of some number of digits and/or punctuation characters, and so forth. See the section for details and an example.

The attribute is a string that provides a brief hint to the user as to what kind of information is expected in the field. It should be a word or short phrase that demonstrates the expected type of data, rather than an explanatory message. The text must not include carriage returns or line feeds.

If the control’s content has one directionality (LTR or RTL) but needs to present the placeholder in the opposite directionality, you can use Unicode bidirectional algorithm formatting characters to override directionality within the placeholder; see in The Unicode Bidirectional Text Algorithm for those characters.

Note: Avoid using the attribute if you can. It is not as semantically useful as other ways to explain your form, and can cause unexpected technical issues with your content. See in <input>: The Input (Form Input) element for more information.

Note: Because a read-only field cannot have a value, does not have any effect on inputs with the attribute also specified.

The attribute is a numeric value indicating how many characters wide the input field should be. The value must be a number greater than zero, and the default value is 20. Since character widths vary, this may or may not be exact and should not be relied upon to be so; the resulting input may be narrower or wider than the specified number of characters, depending on the characters and the font ( settings in use).

This does not set a limit on how many characters the user can enter into the field. It only specifies approximately how many can be seen at a time. To set an upper limit on the length of the input data, use the attribute.

Развертывание портала самостоятельного сброса пароля MIM с помощью Azure MFA для многофакторной идентификацииDeploying MIM Self-Service Password Reset Portal using Azure MFA for Multi-Factor Authentication

Далее описывается развертывание портала самостоятельного сброса пароля MIM с помощью Azure MFA для многофакторной идентификации.The following section describes how to deploy MIM self-service password reset portal, using Azure MFA for multi-factor authentication. Эти действия необходимо выполнить клиентам, не использующим самостоятельный сброс пароля Azure AD для пользователей.These steps are only necessary for customers who are not using Azure AD self-service password reset for their users.

Многофакторная идентификация Microsoft Azure — это служба проверки подлинности, которая требует, чтобы пользователи подтверждали вход с помощью мобильного приложения, звонка с мобильного телефона или текстового сообщения.Microsoft Azure Multi-Factor Authentication is an authentication service that requires users to verify their sign-in attempts with a mobile app, phone call, or text message. Она доступна для использования с Microsoft Azure Active Directory, а также как служба для облачных и локальных корпоративных приложений.It is available to use with Microsoft Azure Active Directory, and as a service for cloud and on-prem enterprise applications.

Azure MFA обеспечивает дополнительный механизм проверки подлинности, который может дополнять имеющиеся процессы проверки подлинности, например процедуру, выполняемую службой MIM для самостоятельной помощи по входу.Azure MFA provides an additional authentication mechanism that can reinforce existing authentication processes, such as the one carried out by MIM for self-service login assistance.

При использовании Azure MFA пользователи проходят проверку подлинности в системе, чтобы подтвердить свою личность при попытке восстановить доступ к учетной записи и ресурсам.When using Azure MFA, users authenticate with the system in order to verify their identity while trying to regain access to their account and resources. Проверку подлинности можно выполнять с помощью SMS или по телефонуAuthentication can be via SMS or via telephone call. Чем строже проверка подлинности, тем выше уверенность в том, что учетная запись действительно принадлежит пользователю, который пытается получить доступ.The stronger the authentication, the higher the confidence that the person trying to gain access is indeed the real user who owns the identity. Пройдя проверку подлинности, пользователь может выбрать новый пароль на замену старому.Once authenticated, the user can choose a new password to replace the old one.

Through phpMyAdmin # Through phpMyAdmin

This article is for those who have phpMyAdmin access to their database. Note: use phpMyAdmin at your own risk. If you doubt your ability to use it, seek further advice. WordPress is not responsible for loss of data.

  1. Begin by logging into phpMyAdmin and clicking databases.
  2. A list of databases will appear. Click on your WordPress database.

phpMyAdmin database select

  1. All the tables in your database will appear. If not, click Structure.
  2. Look for wp_users in the Table column.
  3. Click on the icon for browse.
  4. Locate your username under user_login
  5. Click edit (may look like a pencil icon in some versions of phpMyAdmin).

phpMyAdmin select users table

  1. Your user_id will be shown. Click on Edit.
  2. Next to the user_pass is a long list of numbers and letters.
  3. Select and delete these and type in your new password.
  4. Type in the password you want to use. You can type it in normally–but remember, it is case-sensitive.
  5. In this example, the new password will be ‘rabbitseatcarrots.’
  6. Once you have done that, click the dropdown menu indicated, and select MD5 from the menu.

phpMyAdmin select MD5 function on user_pass row

  1. Check that your password is actually correct, and that MD5 is in the box.

phpMyAdmin user_pass row with MD5 function and “rabbitseatcarrots” as the password

  1. Click the ‘Go’ button to the bottom right.
  2. Test the new password on the login screen. If it doesn’t work, check that you’ve followed these instructions exactly.

How can I reset my MySQL password?

Following this procedure, you will disable access control on the MySQL server. All connexions will have a root access. It is a good thing to unplug your server from the network or at least disable remote access.

To reset your mysqld password just follow these instructions :

  • Stop the mysql demon process using this command :

    sudo /etc/init.d/mysql stop

  • Start the mysqld demon process using the —skip-grant-tables option with this command

    sudo /usr/sbin/mysqld —skip-grant-tables —skip-networking &

Because you are not checking user privs at this point, it’s safest to disable networking. In Dapper, /usr/bin/mysqld… did not work. However, mysqld --skip-grant-tables did.

  • start the mysql client process using this command

    mysql -u root

  • from the mysql prompt execute this command to be able to change any password


  • Then reset/update your password

    SET PASSWORD FOR root@’localhost’ = PASSWORD(‘password’);

  • If you have a mysql root account that can connect from everywhere, you should also do:

    UPDATE mysql.user SET Password=PASSWORD(‘newpwd’) WHERE User=’root’;

  • Alternate Method:

    USE mysql UPDATE user SET Password = PASSWORD(‘newpwd’) WHERE Host = ‘localhost’ AND User = ‘root’;

  • And if you have a root account that can access from everywhere:

    USE mysql UPDATE user SET Password = PASSWORD(‘newpwd’) WHERE Host = ‘%’ AND User = ‘root’;

For either method, once have received a message indicating a successful query (one or more rows affected), flush privileges:


Then stop the mysqld process and relaunch it with the classical way:

sudo /etc/init.d/mysql stop
sudo /etc/init.d/mysql start

When you have completed all this steps ,you can easily access to your mysql server with the password you have set in the step before. An easy way to have a full control of your mysql server is phpmyadmin (www.phpmyadmin.net), software made in php that can give you a web interface that can be very usefull to people that havent got a lot of confidence with bash .To install phpmyadmin on you server you will need to have 4 things:

  • web server apache
  • php
  • mysql server/mysql client installed
  • php_mysql support for apache

All packages can be found browsing synaptic.

Шаг 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)

Through MySQL Command Line # Through MySQL Command Line

  1. Get an MD5 hash of your password.
    • Visit md5 Hash Generator, or…
    • Create a key with Python, or…
    • On Unix/Linux:
      1. Create a file called wp.txt, containing nothing but the new password.
      2. tr -d ‘\r\n’ < wp.txt | md5sum | tr -d ‘ -‘
      3. rm wp.txt
    • On Mac OS X:
      1. Create a file called wp.txt, containing nothing but the new password. Then enter either of the lines below
      2. md5 -q ./wp.txt; rm ./wp.txt (If you want the MD5 hash printed out.)
      3. md5 -q ./wp.txt | pbcopy; rm ./wp.txt (If you want the MD5 hash copied to the clipboard.)
  2. “mysql -u root -p” (log in to MySQL)
  3. enter your mysql password
  4. “use (name-of-database)” (select WordPress database)
  5. “show tables;” (you’re looking for a table name with “users” at the end)
  6. “SELECT ID, user_login, user_pass FROM (name-of-table-you-found);” (this gives you an idea of what’s going on inside)
  7. “UPDATE (name-of-table-you-found) SET user_pass=”(MD5-string-you-made)” WHERE ID = (id#-of-account-you-are-reseting-password-for);” (actually changes the password)
  8. “SELECT ID, user_login, user_pass FROM (name-of-table-you-found);” (confirm that it was changed)
  9. (type Control-D to exit mysql client)

Note: if you have a recent version of MySQL (version 5.x?) you can have MySQL compute the MD5 hash for you.

  1. Skip step# 1 above.
  2. Do the following for step# 7 instead.

Note that even if the passwords are salted, meaning they look like $P$BLDJMdyBwegaCLE0GeDiGtC/mqXLzB0, you can still replace the password with an MD5 hash, and WordPress will let you log in.

Browser compatibility

The compatibility table on this page is generated from structured data. If you’d like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request.

Update compatibility data on GitHub

Chrome Edge Firefox Internet Explorer Opera Safari Android webview Chrome for Android Firefox for Android Opera for Android Safari on iOS Samsung Internet
Chrome Full support 1 Edge Full support 12 Firefox Full support 1 IE Full support 2 Opera Full support 2 Safari Full support 1 WebView Android ? Chrome Android Full support Yes Firefox Android Full support 4 Opera Android Full support Yes Safari iOS Full support Yes Samsung Internet Android Full support Yes
Special handling of password inputs in insecure login pages Non-standard Chrome No support No Edge No support No Firefox Full support 52 IE No support No Opera No support No Safari No support No WebView Android No support No Chrome Android No support No Firefox Android Full support 52 Opera Android No support No Safari iOS No support No Samsung Internet Android No support No

Пожалуйста, помогите c переводом:

Policy – Forestry Commission England continues to take the lead on grey squirrel policy on behalf of Defra. Английский-Русский

In the UK and the USA, law degree programmes usually take three years to complete. In the UK, these programmes typically include core subjects such as criminal law, contract law, tort law, land law, equity and trusts, administrative law and constitutional law. In addition, students ar Английский-Русский

Giving a definition of the term “comedy”, one may face some difficulties as it’s one of the most complex categories of aesthetics. Comedy is historically volatile, it depends on the context and has a social nature. The laughter is not always a sight of comedy, and comedy is not always defined by laughter. It is circumstances, sharpening the contradictions and helping to reveal its social nature Английский-Русский

It slides comfortably into the ‘affordable’ bracket though, considering its supersized display, and when it lands on contract (which should be soon) it won’t carry hefty monthly fees. Английский-Русский

Set the password expiration policy for individual users

A global admin for a Microsoft cloud service can use the Azure Active Directory PowerShell for Graph to set passwords not to expire for specific users. You can also use AzureAD cmdlets to remove the never-expires configuration or to see which user passwords are set to never expire.

This guide applies to other providers, such as Intune and Microsoft 365, which also rely on Azure AD for identity and directory services. Password expiration is the only part of the policy that can be changed.

For more information about Azure AD PowerShell for Graph, see Azure Active Directory PowerShell for Graph.


Only passwords for user accounts that are not synchronized through directory synchronization can be configured to not expire. For more information about directory synchronization, see Connect AD with Azure AD.

How to check the expiration policy for a password

For more information about the Get-AzureADUser command in the AzureAD module, see the reference article Get-AzureADUser.

Run one of the following commands:

  • To see if a single user’s password is set to never expire, run the following cmdlet by using the UPN (for example, *user@contoso.onmicrosoft.com*) or the user ID of the user you want to check:


  • To see the Password never expires setting for all users, run the following cmdlet:

  • To get a report of all the users with PasswordNeverExpires in Html on the desktop of the current user with name ReportPasswordNeverExpires.html

  • To get a report of all the users with PasswordNeverExpires in CSV on the desktop of the current user with name ReportPasswordNeverExpires.csv

Set a password to expire

Run one of the following commands:

  • To set the password of one user so that the password expires, run the following cmdlet by using the UPN or the user ID of the user:

  • To set the passwords of all users in the organization so that they expire, use the following cmdlet:

Set a password to never expire

Run one of the following commands:

  • To set the password of one user to never expire, run the following cmdlet by using the UPN or the user ID of the user:

  • To set the passwords of all the users in an organization to never expire, run the following cmdlet:

Шаг 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

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

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

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


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

Для 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';

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


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

Query OK, 0 rows affected (0.02 sec)

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


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

Using the Emergency Password Reset Script # Using the Emergency Password Reset Script

If the other solutions listed above won’t work, then try the Emergency Password Reset Script. Please note that it’s not a plugin, it’s a PHP script.

A Word of Caution:

  1. The Emergency Password Reset Script requires that you know the administrator’s username.
  2. It updates the administrator password and sends an email to the administrator’s email address.
  3. Even if you don’t receive the email, the password will still be changed.
  4. You do not need to be logged in to use it. (After all, if you could login, you wouldn’t need the script.)
  5. Place the script in the root of your WordPress installation. Do not upload it to your WordPress Plugins directory.
  6. For security reasons, remember to delete the script when you are done.

Directions for Use:

  1. Copy the emergency script from Emergency Password Script and put into a file called emergency.php in the root of your WordPress installation (the same directory that contains wp-config.php).
  2. In your browser, open http://example.com/emergency.php.
  3. As instructed, enter the administrator username (usually admin) and the new password, then click Update Options. A message is displayed noting the changed password. An email is sent to the blog administrator with the changed password information.
  4. Delete emergency.php from your server when you are done. Do not leave it on your server, as someone else could use it to change your password.

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

Самые современные дистрибутивы Linux поставляются с MySQL или MariaDB, последняя является полностью совместимой заменой MySQL. В зависимости от используемой СУБД и её версии, вам нужно использовать различные команды для восстановления пароля рута.

Вы можете проверить вашу версию следующей командой:

mysql --version

Для MySQL вы увидите что-то вроде:

mysql  Ver 14.14 Distrib 5.7.17, for Linux (x86_64) using  EditLine wrapper

Для MariaDB вывод будет примерно таким:

mysql  Ver 15.1 Distrib 10.0.29-MariaDB, for debian-linux-gnu (x86_64) using readline 5.2

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

Another way, purge

I also had some problems with mysql just not accepting my password. I tried the other way as well and it just ended up being difficult. I had not been able to use mysql so it was empty anyway. If this is also your case you may opt for the PURGE way. This removes every file related to mysql. Depending on your installation the packages might be diffrent, mysql-server in 6.10 is called mysql-server-5.0 as an example.


sudo apt-get --purge remove mysql-server mysql-common mysql-client
sudo apt-get install mysql-server mysql-common mysql-client

In the next step be sure to chance the your-new-password with the password you want!

mysqladmin -u root password your-new-password
sudo /etc/init.d/mysql restart
mysql -u root -p

You should now be logged in as root. Make sure to notedown your password! Thanks to Illuvator for posting this method in the ubuntu forum.


If your application has character set restrictions or any other requirement for the actual content of the entered password, you can use the attribute to establish a regular expression to be used to automatically ensure that your passwords meet those requirements.

In this example, only values consisting of at least four and no more than eight hexadecimal digits are valid.

<label for="hexId">Hex ID: </label>
<input id="hexId" type="password" pattern="{4,8}"
       title="Enter an ID consisting of 4-8 hexadecimal digits"

This Boolean attribute indicates that the password field is not available for interaction. Additionally, disabled field values aren’t submitted with the form.

Как это работает для пользователей?How does it work for your users?

Теперь, когда все настроено и запущено, вам может быть интересно, что приходится делать пользователю, если он сбросить свой пароль прямо перед отпуском, а затем вернется и поймет, что совсем забыл его.Now that everything is configured and it’s running, you might want to know what your users are going to have to go through when they reset their passwords right before a vacation and come back only to realize that they completely forgot their passwords.

Пользователь может сбросить пароль и разблокировать учетную запись двумя способами: на экране входа Windows или на портале самообслуживания.There are two ways a user can use the password reset and account unlock functionality, either from the Windows sign-in screen, or from the self-service portal.

После установки надстроек и расширений службы MIM на компьютере домена, который подключен через сеть организации к службе MIM, пользователи могут восстанавливать забытый пароль с рабочего стола своего компьютера.By installing the MIM Add-ins and Extensions on a domain joined computer connected over your organizational network to the MIM Service, users can recover from a forgotten password at the desktop login experience. Следующие действия позволяют завершить указанный процесс.The following steps will walk you through the process.

Changing the MySQL root user password

To reset the password for MySQL you first must create a new file with the following contents:


Where PASSWORD is the new password to be used. Save that file as ~/mysql-pwd.

Next, stop the MySQL daemon with the command:

sudo systemctl stop mysql

With the daemon stopped, issue the command:

sudo mysqld -init-file=~/mysql-pwd

Once your command prompt is returned, restart the MySQL daemon with the command:

sudo systemctl start mysql

You should now be able to log into the MySQL command prompt with the new admin password like so:

mysql -u root -p

When prompted, type the admin password and you’re good to go.

Recover your MySQL password

What if you’ve forgotten your MySQL root user password? This could be quite the predicament … had the developers not thought of that eventuality. In order to recover the password, you simply have to follow these steps:

  1. Stop the MySQL server process with the command sudo service mysql stop
  2. Start the MySQL server with the command sudo mysqld_safe —skip-grant-tables —skip-networking &
  3. Connect to the MySQL server as the root user with the command mysql -u root

At this point, you need to issue the following MySQL commands to reset the root password:

mysql> use mysql;
​mysql> update user set authentication_string=password('NEWPASSWORD') where user='root';
​mysql> flush privileges;
​mysql> quit

Where NEWPASSWORD is the new password to be used.

Restart the MySQL daemon with the command sudo service mysql restart. You should now be able to log into MySQL with the new password.

And that’s it. You can now set, reset, and recover your MySQL password.

SEE: The cloud v. data center decision (ZDNet/TechRepublic special report) | Download the free PDF version (TechRepublic)

С этим читают