Apply security settings mysql ошибка 1045

This solution worked for me (http://dev.mysql.com/doc/refman/5.5/en/resetting-permissions.html) :

C.5.4.1.1. Resetting the Root Password: Windows Systems

On Windows, use the following procedure to reset the password for all MySQL root accounts:

Log on to your system as Administrator.

Stop the MySQL server if it is running. For a server that is running as a Windows service, go to the Services manager: From the Start menu, select Control Panel, then Administrative Tools, then Services. Find the MySQL service in the list and stop it.

If your server is not running as a service, you may need to use the Task Manager to force it to stop.

Create a text file containing the following statements. Replace the password with the password that you want to use.

UPDATE mysql.user SET Password=PASSWORD('MyNewPass') WHERE User='root';
FLUSH PRIVILEGES;

Write the UPDATE and FLUSH statements each on a single line. The UPDATE statement resets the password for all root accounts, and the FLUSH statement tells the server to reload the grant tables into memory so that it notices the password change.

Save the file. For this example, the file will be named C:\mysql-init.txt.

Open a console window to get to the command prompt: From the Start menu, select Run, then enter cmd as the command to be run.

Start the MySQL server with the special —init-file option (notice that the backslash in the option value is doubled):

C:\> C:\mysql\bin\mysqld --init-file=C:\\mysql-init.txt

If you installed MySQL to a location other than C:\mysql, adjust the command accordingly.

The server executes the contents of the file named by the —init-file option at startup, changing each root account password.

You can also add the —console option to the command if you want server output to appear in the console window rather than in a log file.

If you installed MySQL using the MySQL Installation Wizard, you may need to specify a —defaults-file option:

C:\> "C:\Program Files\MySQL\MySQL Server 5.5\bin\mysqld.exe"
         --defaults-file="C:\\Program Files\\MySQL\\MySQL Server 5.5\\my.ini"
         --init-file=C:\\mysql-init.txt

The appropriate —defaults-file setting can be found using the Services Manager: From the Start menu, select Control Panel, then Administrative Tools, then Services. Find the MySQL service in the list, right-click it, and choose the Properties option. The Path to executable field contains the —defaults-file setting.

After the server has started successfully, delete C:\mysql-init.txt.

You should now be able to connect to the MySQL server as root using the new password. Stop the MySQL server, then restart it in normal mode again. If you run the server as a service, start it from the Windows Services window. If you start the server manually, use whatever command you normally use.

This solution worked for me (http://dev.mysql.com/doc/refman/5.5/en/resetting-permissions.html) :

C.5.4.1.1. Resetting the Root Password: Windows Systems

On Windows, use the following procedure to reset the password for all MySQL root accounts:

Log on to your system as Administrator.

Stop the MySQL server if it is running. For a server that is running as a Windows service, go to the Services manager: From the Start menu, select Control Panel, then Administrative Tools, then Services. Find the MySQL service in the list and stop it.

If your server is not running as a service, you may need to use the Task Manager to force it to stop.

Create a text file containing the following statements. Replace the password with the password that you want to use.

UPDATE mysql.user SET Password=PASSWORD('MyNewPass') WHERE User='root';
FLUSH PRIVILEGES;

Write the UPDATE and FLUSH statements each on a single line. The UPDATE statement resets the password for all root accounts, and the FLUSH statement tells the server to reload the grant tables into memory so that it notices the password change.

Save the file. For this example, the file will be named C:\mysql-init.txt.

Open a console window to get to the command prompt: From the Start menu, select Run, then enter cmd as the command to be run.

Start the MySQL server with the special —init-file option (notice that the backslash in the option value is doubled):

C:\> C:\mysql\bin\mysqld --init-file=C:\\mysql-init.txt

If you installed MySQL to a location other than C:\mysql, adjust the command accordingly.

The server executes the contents of the file named by the —init-file option at startup, changing each root account password.

You can also add the —console option to the command if you want server output to appear in the console window rather than in a log file.

If you installed MySQL using the MySQL Installation Wizard, you may need to specify a —defaults-file option:

C:\> "C:\Program Files\MySQL\MySQL Server 5.5\bin\mysqld.exe"
         --defaults-file="C:\\Program Files\\MySQL\\MySQL Server 5.5\\my.ini"
         --init-file=C:\\mysql-init.txt

The appropriate —defaults-file setting can be found using the Services Manager: From the Start menu, select Control Panel, then Administrative Tools, then Services. Find the MySQL service in the list, right-click it, and choose the Properties option. The Path to executable field contains the —defaults-file setting.

After the server has started successfully, delete C:\mysql-init.txt.

You should now be able to connect to the MySQL server as root using the new password. Stop the MySQL server, then restart it in normal mode again. If you run the server as a service, start it from the Windows Services window. If you start the server manually, use whatever command you normally use.

Страницы 1

Чтобы отправить ответ, вы должны войти или зарегистрироваться

1 2010-02-18 16:34:20

  • mkostil
  • Редкий гость
  • Неактивен
  • Зарегистрирован: 2010-02-18
  • Сообщений: 5

Тема: Проблема при настройке mysql

При настройке, установив пароль, в окне processing configuration…, не выполняется пункт — Apply security settings. Я удалял мускл по-новому ставил, и так раз 5, потом решил попробовать как оно будет работать.
Запустил скрипт:
<?php
echo «php работает»;
$link=mysql_connect(«localhost»,»root»,»slagiotore»);

?>
Выдало:php работает
Warning: mysql_connect() [function.mysql-connect]: Access denied for user ‘root’@’localhost’ (using password: YES) in C:\apache\localhost\www\index.php on line 11
При запуске phpmyadmin выдаёт вот такое:

Добро пожаловать в phpMyAdmin

Ошибка

Ответ MySQL: Документация
#1045 — Access denied for user ‘root’@’localhost’ (using password: YES)
phpMyAdmin не смог установить соединение с сервером MySQL. Проверьте хост, имя пользователя и пароль установленные в конфигурационном файле config.inc.php и удостоверьтесь, что они соответствуют данным полученным от администратора сервера MySQL.
Помогите пожалуйста новичку.

2 Ответ от Hanut 2010-02-18 17:17:52

  • Hanut
  • Hanut
  • Модератор
  • На форуме
  • Откуда: Рига, Латвия
  • Зарегистрирован: 2006-07-02
  • Сообщений: 9,726

Re: Проблема при настройке mysql

mkostil
Обычно выдает ошибку в пункте Apply security settings, если брандмауэр блокирует порт MySQL (3306).

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

3 Ответ от mkostil 2010-02-20 02:57:39

  • mkostil
  • Редкий гость
  • Неактивен
  • Зарегистрирован: 2010-02-18
  • Сообщений: 5

Re: Проблема при настройке mysql

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

4 Ответ от Hanut 2010-02-20 11:57:33

  • Hanut
  • Hanut
  • Модератор
  • На форуме
  • Откуда: Рига, Латвия
  • Зарегистрирован: 2006-07-02
  • Сообщений: 9,726

Re: Проблема при настройке mysql

mkostil
Пробуйте запустить сервис MySQL из Control Panel -> Administrative Tools -> Services. Если не запустится, смотрите ошибки в журнале операционной системы или в журнале ошибок MySQL.

5 Ответ от mkostil 2010-02-20 12:57:26

  • mkostil
  • Редкий гость
  • Неактивен
  • Зарегистрирован: 2010-02-18
  • Сообщений: 5

Re: Проблема при настройке mysql

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

6 Ответ от mkostil 2010-02-20 13:13:40

  • mkostil
  • Редкий гость
  • Неактивен
  • Зарегистрирован: 2010-02-18
  • Сообщений: 5

Re: Проблема при настройке mysql

Hanut
При первой установке mysql, не исключаю, что мог натупить с паролями, читал что может самая первая БД не удаляться и из-за этого такая петрушка. Если это действительно так, то как мне её найти и удалить. Я удаляю мускл с панели управления + с програм файлс папку мускл.

7 Ответ от Hanut 2010-02-20 20:26:50

  • Hanut
  • Hanut
  • Модератор
  • На форуме
  • Откуда: Рига, Латвия
  • Зарегистрирован: 2006-07-02
  • Сообщений: 9,726

Re: Проблема при настройке mysql

Попробуйте зайти в MySQL из командной строки (cmd).
mysql -uroot -ppassword

Вместо password введите пароль пользователя root (ключ -p и последующий пароль должны быть вплотную, как написано).

Если захотите переустановить MySQL, то удалить надо так же каталог data, который находится здесь: C:\Documents and Settings\All Users\Application Data\MySQL\MySQL Server 5.1\data

8 Ответ от pau4ok 2010-02-21 15:06:55

  • pau4ok
  • Редкий гость
  • Неактивен
  • Откуда: г. Одесса
  • Зарегистрирован: 2010-02-21
  • Сообщений: 2

Re: Проблема при настройке mysql

У меня точно такая жа проблема, переустановил маскл но всеравно пишет, что не открыт порт. Возможно проблема в том что у меня роутер, но в его настройках я открыл порт 3306. Если через командную строку заходить то выбивает тот же эрор:
#1045 — Access denied for user ‘root’@’localhost’ (using password: YES)

9 Ответ от Hanut 2010-02-21 16:30:12

  • Hanut
  • Hanut
  • Модератор
  • На форуме
  • Откуда: Рига, Латвия
  • Зарегистрирован: 2006-07-02
  • Сообщений: 9,726

Re: Проблема при настройке mysql

pau4ok сказал:

#1045 — Access denied for user ‘root’@’localhost’ (using password: YES)

Это означает, что MySQL работает, но пароль не принимается.

10 Ответ от pau4ok 2010-02-21 16:35:43

  • pau4ok
  • Редкий гость
  • Неактивен
  • Откуда: г. Одесса
  • Зарегистрирован: 2010-02-21
  • Сообщений: 2

Re: Проблема при настройке mysql

Ммм и что делать?)

11 Ответ от Hanut 2010-02-21 17:20:06

  • Hanut
  • Hanut
  • Модератор
  • На форуме
  • Откуда: Рига, Латвия
  • Зарегистрирован: 2006-07-02
  • Сообщений: 9,726

Re: Проблема при настройке mysql

pau4ok
Попробуйте переустановить MySQL удалив сперва каталог data.

12 Ответ от mkostil 2010-02-21 17:28:10

  • mkostil
  • Редкий гость
  • Неактивен
  • Зарегистрирован: 2010-02-18
  • Сообщений: 5

Re: Проблема при настройке mysql

Hanut
ОГРОМНЕЙШЕЕ СПАСИБО!!!!!!!!!!!!!!!
Переустановил я мускл, а перед этим удалил каталог, правда не data а MySql в которой находиться data, я думаю разницы нет, и все прошло как по маслу. Только если кто-то столкнётся с этой проблемой, перегрузите комп, а то я сразу обрадовался конфигурация прошла успешно, а не тестовый скрипт не хотел работать, на phpmyadmin зашёл за 3 разом, а после перезагрузки всё работает. Hanut ещё раз тебе спасибо.

13 Ответ от Skolzkiy 2011-04-11 19:45:44

  • Skolzkiy
  • Редкий гость
  • Неактивен
  • Зарегистрирован: 2011-04-11
  • Сообщений: 3

Re: Проблема при настройке mysql

Народ..выручайте)
У меня тоже возникает проблема на этом месте….но с другой ошибкой
The securite setting could not be applied to the database the conection has faild with the following error.

Error Nr. 2003
Can’t connect to MySQL server on ‘localhost'(10061)

И там ещё много чего…)
Кто может сказать в чём проблема..я уже переустанавливал программу 10 раз…перезагружал, порт открывал…но толку 0…а вот как указано с папкой data, дак её я не нашёл вообще….искал в корне где установлена программа, но там были только….bin, lib, share….и ещё разные файлы…версия программы 5.1ююю
Заранее спасибки;)

14 Ответ от DiapaZon 2011-04-11 20:36:04

  • DiapaZon
  • Редкий гость
  • Неактивен
  • Зарегистрирован: 2011-04-11
  • Сообщений: 2

Re: Проблема при настройке mysql

Подскажите пожалуйста как мне изменить сохранения БД из C:\Documents and Settings\All Users\Application Data\MySQL Server 5.1\data в C\MySQL5\data Заранее спасибо) sad

15 Ответ от Hanut 2011-04-11 21:59:36

  • Hanut
  • Hanut
  • Модератор
  • На форуме
  • Откуда: Рига, Латвия
  • Зарегистрирован: 2006-07-02
  • Сообщений: 9,726

Re: Проблема при настройке mysql

Skolzkiy сказал:

с папкой data, дак её я не нашёл вообще

Ищите где-то здесь.
C:/Documents and Settings/All Users/Application Data/MySQL/MySQL Server 5.5/Data/

16 Ответ от Hanut 2011-04-11 22:00:46

  • Hanut
  • Hanut
  • Модератор
  • На форуме
  • Откуда: Рига, Латвия
  • Зарегистрирован: 2006-07-02
  • Сообщений: 9,726

Re: Проблема при настройке mysql

DiapaZon сказал:

Подскажите пожалуйста как мне изменить сохранения БД из C:\Documents and Settings\All Users\Application Data\MySQL Server 5.1\data в C\MySQL5\data Заранее спасибо) sad

В my.ini директива datadir.

17 Ответ от Skolzkiy 2011-04-11 22:12:27

  • Skolzkiy
  • Редкий гость
  • Неактивен
  • Зарегистрирован: 2011-04-11
  • Сообщений: 3

Re: Проблема при настройке mysql

Hanut сказал:

Ищите где-то здесь.
C:/Documents and Settings/All Users/Application Data/MySQL/MySQL Server 5.5/Data/

В том то и дело..я при установки путь не менял..и он по стандарту в C фигачил…установил 66 версию..папка дата появляется….но удаляю её..но толку от этого 0…(
ставлю заново мускл..но всё равно ошибку выдаёт…и я так понимаю, ругается он на порт((((
А да…и по чему то, после удаления… остается название серва…т.е. нельзя его больше создать…так как он уже существует…..я хз вообще чё делать…(

18 Ответ от Hanut 2011-04-11 23:31:34

  • Hanut
  • Hanut
  • Модератор
  • На форуме
  • Откуда: Рига, Латвия
  • Зарегистрирован: 2006-07-02
  • Сообщений: 9,726

Re: Проблема при настройке mysql

Skolzkiy сказал:

и по чему то, после удаления… остается название серва

Это я не понял. Где остается? Если остается сервис MySQL, значит вы его не удалили.

19 Ответ от DmitryV 2011-04-12 10:45:13

  • DmitryV
  • Пенсионер
  • Неактивен
  • Откуда: Санкт-Петербург, Россия
  • Зарегистрирован: 2010-07-31
  • Сообщений: 558

Re: Проблема при настройке mysql

MySQL версию выше 5.5 не устанавливайте 6 это сырые беты.

20 Ответ от Skolzkiy 2011-04-12 10:52:15

  • Skolzkiy
  • Редкий гость
  • Неактивен
  • Зарегистрирован: 2011-04-11
  • Сообщений: 3

Re: Проблема при настройке mysql

Hanut сказал:

Это я не понял. Где остается? Если остается сервис MySQL, значит вы его не удалили.

Ну при настройках там есть название типа сервиса…ну вот там и остаётся по чему то…хотя через панель программа ыла удалена…

DmitryV сказал:

MySQL версию выше 5.5 не устанавливайте 6 это сырые беты.

Спасибки…буду знать)

Страницы 1

Чтобы отправить ответ, вы должны войти или зарегистрироваться

The MySQL Error 1045 typically occurs when you attempt to access your MySQL database through WordPress. The request will be denied if the server doesn’t think you’re authorized to perform the action. For instance, you might be using the wrong password or you might not have the required permissions.

Fortunately, there are plenty of ways to fix the MySQL 1045 Error. For example, you can reset your password, check on the user permissions, and verify the port.

In this post, we’ll take a closer look at MySQL Error 1045 and discuss some common causes. Then, we’ll guide you through four methods to fix the error. Let’s get started!

What Is the MySQL 1045 Error?

This error comes in a number of forms, but throughout this post, we’ll refer to it as MySQL Error 1045. However, the error may also present as “Error 1045 (28000) access denied for user root localhost”:

An example of the MySQL 1045 Error

MySQL 1045 Error

Typically, you’ll see the MySQL 1045 Error when you try to access the MySQL database through WordPress. MySQL is the database system that is used to add, access, and manage content in your WordPress website.

Other popular databases that use MySQL are MariaDB and SQLite. MongoDB on the other hand is a schema less NoSQL database, so you won’t find the 1045 error when using it.

When you encounter this error message, it indicates that you aren’t authorized to access the database from localhost. For example, you may be using the wrong password, or wrong username, or have insufficient permissions.

MySQL server port issues? It might be the cause of that pesky MySQL 1045 Error. This guide can help! 🔧💡Click to Tweet

What Are the Causes of the MySQL Error 1045?

Here are some of the main causes of MySQL Error 1045:

  • Insufficient permissions. You won’t be granted access to the MySQL database if you don’t have the necessary WordPress permissions.
  • User doesn’t exist. You’ll also see the error if you’re not registered as a user on the server. In this instance, the database simply doesn’t know of your existence.
  • Incorrect login credentials. The cause of the error may be something as simple as using the wrong password and username. This can often be the case if you have multiple hosts since it’s easy to mix up your passwords.
  • Wrong host. If you don’t specify the host to connect with, MySQL will attempt to connect to localhost. Meanwhile, you might be trying to connect to a different host or port.
  • Bash interference. Special characters in the password can be converted by Bash. However, you can wrap the password in single quotes to avoid this.
  • No SSL. In order to access the database, Secure Sockets Layer (SSL) may be required, but you might not have a valid SSL certificate.

Once you’ve identified the cause of the MySQL 1045 Error, you’re in a better position to apply the correct solution. Then, you can clear the error message and get back to work.

How To Fix the MySQL 1045 Error (4 Methods)

Now that you know a bit more about MySQL Error 1045, let’s take a look at four simple methods to fix it.

1. Verify that the User Has the Necessary Privileges

One of the main causes of the MySQL 1045 Error is that the user “root” does not have the necessary permissions. So, the first thing you’ll want to do is check the status of these privileges.

You can check the user permissions by opening your terminal and entering the following:

ssh username@ipaddress

After successfully logging in, add the following command from the MySQL prompt:

mysql -uroot -p

Then, enter this command to grant all privileges:

GRANT ALL PRIVILEGES ON *.* TO 'root'@'localhost' IDENTIFIED BY 'password';

You can also check the user privileges using phpMyAdmin. In this instance, you’ll need to log into your hosting account and click on the User Accounts tab.

If you’re a Kinsta customer, the process is a little different. Once you’ve logged into your dashboard, go to WordPress Sites and choose the site that you want to check permissions for. Then, in the Info tab, scroll down to Database access:

Open phpMyAdmin from your MyKinsta dashboard

phpMyAdmin in the MyKinsta dashboard

Here, click on the Open phpMyAdmin link. You’ll need to enter your username and password to access the database. Then, select the Users link to manage all your MySQL user accounts.

No matter what hosting provider you use, you’ll need to locate the appropriate user within the database and click on Edit Privileges. Here, you’ll be able to see a list of privileges that the user has been granted.

If the user doesn’t have the required privileges, you can grant them by selecting the relevant check boxes. Then, click on Go to apply your changes. Now, try accessing the database again to see if MySQL Error 1045 has cleared.

2. Make Sure You’re Using the Correct Username and Password

Although it may seem simple, sometimes, the cause of the MySQL 1045 Error is that you’re using incorrect login credentials. Fortunately, you can check this information by consulting your wp-config.php file.

You can find this file by logging into your host’s control panel and accessing a file manager. Or, you can connect to your site via SFTP.

With this approach, you’ll first need to locate the root directory of your site, which is usually labeled public_html. Then, you should find the wp-config.php file inside it:

Locating the wp-config.php file using an FTP client

Locate the wp-config.php file

Open the file and check that the DB_USER and DB_PASSWORD have the correct values. The username is “root.” Meanwhile, the password is the one you set during installation.

If you can’t remember the password you created, you can access cPanel, go to Database, and then click on MySQL. If you’re a Kinsta customer, you can check this information under Info → Database access (see the section above for further details).

3. Reset Your Password

If you can’t remember the password for the database, you can reset it to gain access to MySQL and clear the error. First, you’ll need to access phpMyAdmin.

Next, open the WordPress database from the left of the screen:

View the database tables in phpMyAdmin

Database tables in phpMyAdmin

Here, you’ll have a list of tables containing data that helps your site run smoothly. For instance, you should see wp_comments and wp_posts among others.

At this point, click on wp_users. This should reveal basic user information like usernames, email addresses, and passwords. Find the user listing that you need to change and click on Edit:

Edit a user listing in phpMyAdmin

Edit a user listing in phpMyAdmin

Here, you can change all the details of the user account.

No matter what hosting provider you use, once you’re able to edit the user listing, look out for the user_pass section. This is where you can see the current password for the database:

Reset your MySQL password

Reset your MySQL password

To change the password, click in the text area and simply delete the password and enter a new one.

In the user_pass area, you can also use the Function dropdown menu to select MD5. This will encrypt your password for extra security. Then, click on Go at the bottom of the screen to save your new password.

4. Make Sure the MySQL Server is Listening to the Correct Port

Another quick solution to the MySQL 1045 Error is to make sure the server is listening to the right port. First, though, it’s useful to check that MySQL is running.

You can check the server status by running the following command:

systemtl status MySQL

If the server isn’t running, start it by using this command:

systemtl start MySQL

Now, the default port for MySQL is 3306 so you can make sure it’s running the correct port. Open a terminal or command prompt on the server where MySQL is installed.

Then, connect to the server using this command:

mysql -username -password

Now, type the following command to display the port number that the MySQL server is listening to:

SHOW VARIABLES LIKE ‘port’:

You can change the port parameter here or in the configuration file. Then, restart the MySQL server to apply the changes.

MySQL Error 1045 quick fix: reset password, verify permissions, and check port settings. Read on to learn more 📚Click to Tweet

Summary

WordPress errors can be frustrating and hinder your ability to make important changes to your site. The MySQL 1045 Error is particularly problematic because it stops you from accessing your database. Fortunately, there are ways you can fix it.

For starters, you might need to check that you have the necessary privileges to access the database. Or, it may be a simple case of using the wrong username and password. Alternatively, you can reset your password or check that the MySQL server is listening to the right port.

At Kinsta, all of our plans offer top-quality support to help you troubleshoot issues quickly. What’s more, our database hosting has 25 data centers and 260+ Content Delivery Network (CDN) locations – so it’s fast, secure, and scalable. Check out our plans today!

MySQL 1045 error Access DeniedDuring our work in support, we see this again and again: “I try to connect to MySQL and am getting a 1045 error”, and most times it comes accompanied with “…but I am sure my user and password are OK”.  So we decided it was worth showing other reasons this error may occur.

MySQL 1045 error Access Denied triggers in the following cases:

1) Connecting to wrong host:

[engineer@percona]# mysql -u root -psekret

mysql: [Warning] Using a password on the command line interface can be insecure.

ERROR 1045 (28000): Access denied for user ‘root’@‘localhost’ (using password: YES)

If not specifying the host to connect (with -h flag), MySQL client will try to connect to the localhost instance while you may be trying to connect to another host/port instance.

Fix: Double check if you are trying to connect to localhost, or be sure to specify host and port if it’s not localhost:

[engineer@percona]# mysql -u root -psekret -h <IP> -P 3306

2) User does not exist:

[engineer@percona]# mysql -u nonexistant -psekret -h localhost

mysql: [Warning] Using a password on the command line interface can be insecure.

ERROR 1045 (28000): Access denied for user ‘nonexistant’@‘localhost’ (using password: YES)

Fix: Double check if the user exists:

mysql> SELECT User FROM mysql.user WHERE User=‘nonexistant’;

Empty set (0.00 sec)

If the user does not exist, create a new user:

mysql> CREATE USER ‘nonexistant’@‘localhost’ IDENTIFIED BY ‘sekret’;

Query OK, 0 rows affected (0.00 sec)

3) User exists but client host does not have permission to connect:

[engineer@percona]# mysql -u nonexistant -psekret

mysql: [Warning] Using a password on the command line interface can be insecure.

ERROR 1045 (28000): Access denied for user ‘nonexistant’@‘localhost’ (using password: YES)

Fix: You can check to see which host user/host MySQL allows connections with the following query:

mysql> SELECT Host, User FROM mysql.user WHERE User=‘nonexistant’;

+++

| Host        | User        |

+++

| 192.168.0.1 | nonexistant |

+++

1 row in set (0.00 sec)

If you need to check from which IP the client is connecting, you can use the following Linux commands for server IP:

[engineer@percona]# ip address | grep inet | grep -v inet6

    inet 127.0.0.1/8 scope host lo

    inet 192.168.0.20/24 brd 192.168.0.255 scope global dynamic wlp58s0

or for public IP:

[engineer@percona]# dig +short myip.opendns.com @resolver1.opendns.com

177.128.214.181

You can then create a user with correct Host (client IP), or with ‘%’ (wildcard) to match any possible IP:

mysql> CREATE USER ‘nonexistant’@‘%’ IDENTIFIED BY ‘sekret’;

Query OK, 0 rows affected (0.00 sec)

4) Password is wrong, or the user forgot his password:

[engineer@percona]# mysql -u nonexistant -pforgotten

mysql: [Warning] Using a password on the command line interface can be insecure.

ERROR 1045 (28000): Access denied for user ‘nonexistant’@‘localhost’ (using password: YES)

Fix: Check and/or reset password:

You cannot read user passwords in plain text from MySQL as the password hash is used for authentication, but you can compare hash strings with “PASSWORD” function:

mysql> SELECT Host, User, authentication_string, PASSWORD(‘forgotten’) FROM mysql.user WHERE User=‘nonexistant’;  

+++++

| Host        | User        | authentication_string                     | PASSWORD(‘forgotten’)                     |

+++++

| 192.168.0.1 | nonexistant | *AF9E01EA8519CE58E3739F4034EFD3D6B4CA6324 | *70F9DD10B4688C7F12E8ED6C26C6ABBD9D9C7A41 |

| %           | nonexistant | *AF9E01EA8519CE58E3739F4034EFD3D6B4CA6324 | *70F9DD10B4688C7F12E8ED6C26C6ABBD9D9C7A41 |

+++++

2 rows in set, 1 warning (0.00 sec)

We can see that PASSWORD(‘forgotten’) hash does not match the authentication_string column, which means password string=’forgotten’ is not the correct password to log in. Also, in case the user has multiple hosts (with different password), he may be trying to connect using the password for the wrong host.

In case you need to override the password you can execute the following query:

mysql> set password for ‘nonexistant’@‘%’ = ‘hello$!world’;

Empty set (0.00 sec)

5) Special characters in the password being converted by Bash:

[engineer@percona]# mysql -u nonexistant -phello$!world

mysql: [Warning] Using a password on the command line interface can be insecure.

ERROR 1045 (28000): Access denied for user ‘nonexistant’@‘localhost’ (using password: YES)

Fix: Prevent bash from interpreting special characters by wrapping password in single quotes:

[engineer@percona]# mysql -u nonexistant -p’hello$!world’

mysql: [Warning] Using a password on the command line interface can be insecure

...

mysql>

6) SSL is required but the client is not using it:

mysql> create user ‘ssluser’@‘%’ identified by ‘sekret’;

Query OK, 0 rows affected (0.00 sec)

mysql> alter user ‘ssluser’@‘%’ require ssl;

Query OK, 0 rows affected (0.00 sec)

...

[engineer@percona]# mysql -u ssluser -psekret

mysql: [Warning] Using a password on the command line interface can be insecure.

ERROR 1045 (28000): Access denied for user ‘ssluser’@‘localhost’ (using password: YES)

Fix: Adding –ssl-mode flag (–ssl flag is deprecated but can be used too)

[engineer@percona]# mysql -u ssluser -psekret —ssl-mode=REQUIRED

...

mysql>

You can read more in-depth on how to configure SSL in MySQL in the blog post about “Setting up MySQL SSL and Secure Connections” and “SSL in 5.6 and 5.7“.

7) PAM backend not working:

mysql> CREATE USER ‘ap_user’@‘%’ IDENTIFIED WITH auth_pam;

Query OK, 0 rows affected (0.00 sec)

...

[engineer@percona]# mysql -u ap_user -pap_user_pass

mysql: [Warning] Using a password on the command line interface can be insecure.

ERROR 1045 (28000): Access denied for user ‘ap_user’@‘localhost’ (using password: YES)

Fix: Double check user/password is correct for the user to authenticate with the PAM currently being used.

In my example, I am using Linux shadow files for authentication. In order to check if the user exists:

[engineer@percona]# cat /etc/passwd | grep ap_user

ap_user:x:1000:1000::/home/ap_user:/bin/bash

To reset password:

[engineer@percona]# sudo passwd ap_user

Changing password for user ap_user.

New password:

Finally, if you are genuinely locked out and need to circumvent the authentication mechanisms in order to regain access to the database, here are a few simple steps to do so:

  1. Stop the instance
  2. Edit my.cnf and add skip-grant-tables under [mysqld] (this will allow access to MySQL without prompting for a password). On MySQL 8.0, skip-networking is automatically enabled (only allows access to MySQL from localhost), but for previous MySQL versions it’s suggested to also add –skip-networking under [mysqld]
  3. Start the instance
  4. Access with root user (mysql -uroot -hlocalhost); 
  5. Issue the necessary GRANT/CREATE USER/SET PASSWORD to correct the issue (likely setting a known root password will be the right thing: SET PASSWORD FOR ‘root’@’localhost’ = ‘S0vrySekr3t’). Using grant-skip-tables won’t read grants into memory and GRANT/CREATE/SET PASSWORD statements won’t work straight away. First, you need to execute “FLUSH PRIVILEGES;” before executing any GRANT/CREATE/SET PASSWORD statement, or you can modify mysql.users table with a query which modifies the password for User and Host like “UPDATE mysql.user SET authentication_string=PASSWORD(‘newpwd’) WHERE User=’root’ and Host=’localhost’;”

  6. Stop the instance
  7. Edit my.cnf and remove skip-grant-tables and skip-networking
  8. Start MySQL again
  9. You should be able to login with root from the localhost and do any other necessary corrective operations with root user.

Learn more about Percona Server for MySQL

Понравилась статья? Поделить с друзьями:
  • Appmanage произошла ошибка
  • Application is not available ошибка
  • Application popup 56 windows 10 ошибка
  • Application load error 5 0000065434 готика 3 ошибка
  • Application hang detected fortnite ошибка