Mysql got error 1045

Дата: 25.11.2013

Дата: 25.11.2013

Автор: Василий Лукьянчиков , vl (at) sqlinfo (dot) ru

Статистика форума SQLinfo показывает, что одной из наиболее популярных проблем является ошибка mysql №1045 (ошибка доступа).
Текст ошибки содержит имя пользователя, которому отказано в доступе, компьютер, с которого производилось подключение, а также ключевое слово YES или NO, которые показывают использовался ли при этом пароль или была попытка выполнить подключение с пустым паролем.

Типичные примеры:

ERROR 1045 (28000): Access denied for user ‘root’@‘localhost’ (using password: YES) — сервер MySQL
— сообщает, что была неудачная попытка подключения с локальной машины пользователя с именем root и
— не пустым паролем.

ERROR 1045 (28000): Access denied for user ‘root’@‘localhost’ (using password: NO) — отказано в
— доступе с локальной машины пользователю с именем root при попытке подключения с пустым паролем.

ERROR 1045 (28000): Access denied for user ‘ODBC’@‘localhost’ (using password: NO) — отказано в
— доступе с локальной машины пользователю с именем ODBC при попытке подключения с пустым паролем.

Причина возникновения ошибки 1045

Как ни банально, но единственная причина это неправильная комбинация пользователя и пароля. Обратите внимание, речь идет о комбинации пользователь и пароль, а не имя пользователя и пароль. Это очень важный момент, так как в MySQL пользователь характеризуется двумя параметрами: именем и хостом, с которого он может обращаться. Синтаксически записывается как ‘имя пользователя’@’имя хоста’.

Таким образом, причина возникновения MySQL error 1045 — неправильная комбинация трех параметров: имени пользователя, хоста и пароля.

В качестве имени хоста могут выступать ip адреса, доменные имена, ключевые слова (например, localhost для обозначения локальной машины) и групповые символы (например, % для обозначения любого компьютера кроме локального). Подробный синтаксис смотрите в документации

Замечание: Важно понимать, что в базе не существует просто пользователя с заданным именем (например, root), а существует или пользователь с именем root, имеющий право подключаться с заданного хоста (например, root@localhost) или даже несколько разных пользователей с именем root (root@127.0.0.1, root@webew.ru, root@’мой домашний ip’ и т.д.) каждый со своим паролем и правами.

Примеры.
1) Если вы не указали в явном виде имя хоста

GRANT ALL ON publications.* TO ‘ODBC’ IDENTIFIED BY ‘newpass’;

то у вас будет создан пользователь ‘ODBC’@’%’ и при попытке подключения с локальной машины вы получите ошибку:

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

так как пользователя ‘ODBC’@’localhost’ у вас не существует.

2) Другой первопричиной ошибки mysql 1045 может быть неправильное использование кавычек.

CREATE USER ‘new_user@localhost’ IDENTIFIED BY ‘mypass’; — будет создан пользователь ‘new_user@localhost’@’%’

Правильно имя пользователя и хоста нужно заключать в кавычки отдельно, т.е. ‘имя пользователя’@’имя хоста’

3) Неочевидный вариант. IP адрес 127.0.0.1 в имени хоста соответствует ключевому слову localhost. С одной стороны, root@localhost и ‘root’@’127.0.0.1’ это синонимы, с другой, можно создать двух пользователей с разными паролями. И при подключении будет выбран тот, который распологается в таблице привелегий (mysql.user) раньше.

4) Аккаунт с пустым именем пользователя трактуется сервером MySQL как анонимный, т.е. позволяет подключаться пользователю с произвольным именем или без указания имени.
Например, вы создали пользователя »@localhost с пустым паролем, чтобы каждый мог подключиться к базе. Однако, если при подключении вы укажите пароль отличный от пустого, то получите ошибку 1045. Как говорилось ранее, нужно совпадение трех параметров: имени пользователя, хоста и пароля, а пароль в данном случае не совпадает с тем, что в базе.

Что делать?

Во-первых, нужно убедиться, что вы используете правильные имя пользователя и пароль. Для этого нужно подключиться к MySQL с правами администратора (если ошибка 1045 не дает такой возможности, то нужно перезапустить сервер MySQL в режиме —skip-grant-tables), посмотреть содержимое таблицы user служебной базы mysql, в которой хранится информация о пользователях, и при необходимости отредактировать её.

Пример.

SELECT user,host,password FROM mysql.user;
+—————+——————+——————————————-+
| user          | host            | password                                  |
+—————+——————+——————————————-+
| root          | house-f26710394 | *81F5E21E35407D884A6CD4A731AEBFB6AF209E1B |
| aa            | localhost       | *196BDEDE2AE4F84CA44C47D54D78478C7E2BD7B7 |
| test          | localhost       |                                           |
| new_user      | %               |                                           |
|               | %               | *D7D6F58029EDE62070BA204436DE23AC54D8BD8A |
| new@localhost | %               | *ADD102DFD6933E93BCAD95E311360EC45494AA6E |
| root          | localhost       | *81F5E21E35407D884A6CD4A731AEBFB6AF209E1B |
+—————+——————+——————————————-+

Если изначально была ошибка:

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

    значит вы указывали при подключении неверный пароль, так как пользователь root@localhost существует. Сам пароль храниться в зашифрованном виде и его нельзя узнать, можно лишь задать новый

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

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

    в данном случае в таблице привилегий отсутствует пользователь ‘ODBC’@’localhost’. Его нужно создать, используя команды GRANT, CREATE USER и SET PASSWORD.

Экзотический пример. Устанавливаете новый пароль для root@localhost в режиме —skip-grant-tables, однако после перезагрузки сервера по прежнему возникает ошибка при подключении через консольный клиент:
ERROR 1045 (28000): Access denied for user ‘root’@‘localhost’ (using password: YES)
Оказалось, что было установлено два сервера MySQL, настроенных на один порт.

phpmyadmin

При открытии в браузере phpmyadmin получаете сообщение:

Error
MySQL said:

#1045 — Access denied for user ‘root’@’localhost’ (using password: NO)
Connection for controluser as defined in your configuration failed.
phpMyAdmin tried to connect to the MySQL server, and the server rejected the connection. You should check the host, username and password in your configuration and make sure that they correspond to the information given by the administrator of the MySQL server.

Ни логина, ни пароля вы не вводили, да и пхпадмин их нигде требовал, сразу выдавая сообщение об ошибке. Причина в том, что данные для авторизации берутся из конфигурационного файла config.inc.php Необходимо заменить в нем строчки

$cfg[‘Servers’][$i][‘user’] = ‘root’;      // MySQL user
$cfg[‘Servers’][$i][‘password’] = »;      // MySQL password (only needed

на

$cfg[‘Servers’][$i][‘user’] = ‘ЛОГИН’;      
$cfg[‘Servers’][$i][‘password’] = ‘ПАРОЛЬ’

Установка новой версии

Устанавливаете новую версию MySQL, но в конце при завершении конфигурации выпадает ошибка:

ERROR Nr. 1045
Access denied for user ‘root’@‘localhost’ (using password: NO)

Это происходит потому, что ранее у вас стоял MySQL, который вы удалили без сноса самих баз. Если вы не помните старый пароль и вам нужны эти данные, то выполните установку новой версии без смены пароля, а потом смените пароль вручную через режим —skip-grant-tables.

P.S. Статья написана по материалам форума SQLinfo, т.е. в ней описаны не все потенциально возможные случаи возникновения ошибки mysql №1045, а только те, что обсуждались на форуме. Если ваш случай не рассмотрен в статье, то задавайте вопрос на форуме SQLinfo
Вам ответят, а статья будет расширена.

Дата публикации: 25.11.2013

© Все права на данную статью принадлежат порталу SQLInfo.ru. Перепечатка в интернет-изданиях разрешается только с указанием автора и прямой ссылки на оригинальную статью. Перепечатка в бумажных изданиях допускается только с разрешения редакции.

grep 'temporary password' /var/log/mysqld.log
Sort date (newest date)

You may see something like this;

[root@SERVER ~]# grep 'temporary password' /var/log/mysqld.log
2016-01-16T18:07:29.688164Z 1 [Note] A temporary password is generated for root@localhost: O,k5.marHfFu
2016-01-22T13:14:17.974391Z 1 [Note] A temporary password is generated for root@localhost: b5nvIu!jh6ql
2016-01-22T15:35:48.496812Z 1 [Note] A temporary password is generated for root@localhost: (B*=T!uWJ7ws
2016-01-22T15:52:21.088610Z 1 [Note] A temporary password is generated for root@localhost: %tJXK7sytMJV
2016-01-22T16:24:41.384205Z 1 [Note] A temporary password is generated for root@localhost: lslQDvgwr3/S
2016-01-22T22:11:24.772275Z 1 [Note] A temporary password is generated for root@localhost: S4u+J,Rce_0t
[root@SERVER ~]# mysql_secure_installation

Securing the MySQL server deployment.

Enter password for user root: 

The existing password for the user account root has expired. Please set a new password.

New password: 

Re-enter new password:

If you see it says

... Failed! Error: Your password does not satisfy the current policy requirements
That means your password needs to have a character such as ! . # - etc...
mix characters well, upper case, lower case, ! . , # etc...

New password: 

Re-enter new password: 
The 'validate_password' plugin is installed on the server.
The subsequent steps will run with the existing configuration
of the plugin.
Using existing password for root.

Estimated strength of the password: 100 
Change the password for root ? ((Press y|Y for Yes, any other key for No) : Y

New password: 

Re-enter new password: 

Estimated strength of the password: 100 
Do you wish to continue with the password provided?(Press y|Y for Yes, any other key for No) : Y
By default, a MySQL installation has an anonymous user,
allowing anyone to log into MySQL without having to have
a user account created for them. This is intended only for
testing, and to make the installation go a bit smoother.
You should remove them before moving into a production
environment.

Remove anonymous users? (Press y|Y for Yes, any other key for No) : Y
Success.


Normally, root should only be allowed to connect from
'localhost'. This ensures that someone cannot guess at
the root password from the network.

Disallow root login remotely? (Press y|Y for Yes, any other key for No) : Y
Success.

By default, MySQL comes with a database named 'test' that
anyone can access. This is also intended only for testing,
and should be removed before moving into a production
environment.


Remove test database and access to it? (Press y|Y for Yes, any other key for No) : Y
 - Dropping test database...
Success.

 - Removing privileges on test database...
Success.

Reloading the privilege tables will ensure that all changes
made so far will take effect immediately.

Reload privilege tables now? (Press y|Y for Yes, any other key for No) : Y
Success.

All done! 
[root@SERVER ~]# mysql -u root -p
Enter password: 
Welcome to the MySQL monitor.  Commands end with ; or g.
Your MySQL connection id is 11
Server version: 5.7.10 MySQL Community Server (GPL)

Watch the last 10 minutes of this video, it teaches you how you do it.

Are you looking for a solution to fix the MySQL ERROR 1045 (28000): Access denied for user ‘user’@’localhost’ (using password: YES) error message?

If you’re an experienced MySQL database manager, you may have come across some vague and confusing problems, like MySQL Error 1045 (28000) messages. Fortunately, while resolving this error can be confusing at first due to its many potential causes, its solutions tend to be relatively simple. Once you determine the reason behind the database error you’re seeing, you should be able to fix it fairly quickly.

In this post, we’ll cover the various possible causes of the MySQL Error 1045 (28000). Then we’ll share solutions for each common situation, to help you get your database and your site back up and running.

Why the MySQL Error 1045 (28000) Error Occurs

The MySQL Error 1045 (28000) is an authentication error. «MySQL ERROR 1045 (28000): Access denied for user ‘user’@’localhost’ (using password: YES)» typically indicates that MySQL cannot log you in using the username and password you’ve specified.

This usually occurs when you provide an incorrect username/password combination when making the database connection. However, there are many other different situations that can lead to this type of behaviour.

  • Connecting to the wrong host or port
  • Provided user does not exist
  • User does exist but client host have insufficient permission to connect, or be IP banned
  • Wrong password provided
  • Bash converts special characters in the password to a different encoding

Wrong host or port

If you don’t specify the host to connect (with the -h flag), MySQL client will try to automatically connect to the localhost instance. You may be trying to connect to another host/port instance. In this case, simply add -h flag followed by the hostname you’re trying to connect to.

Code language: HTML, XML (xml)

Also, double check if you are trying to connect to the right port. MySQL, by default, listen on port 3306, but different setups use different ports for security purposes. Providing -P flag and a port number in the command is a great way to remind you of this detail.

[[email protected]]# mysql -u root -psekret -h <IP_or_hostname> -P 3306

Code language: HTML, XML (xml)

Provided user does not exist

MySQL stores user data in a table called user in a database named mysql (by default). The following query will return 1 if a user with the specified username exists, 0 otherwise.

mysql> SELECT EXISTS(SELECT 1 FROM mysql.user WHERE user = 'username') Query OK, 0 rows affected (0.00 sec)

Code language: JavaScript (javascript)

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

mysql> CREATE USER 'username'@'localhost' IDENTIFIED BY 'password'; Query OK, 0 rows affected (0.00 sec)

Code language: JavaScript (javascript)

Client host have insufficient permission

By default, the MySQL server listens for connections only from localhost, which means it can be accessed only by applications running on the same host.

Remote root access is disabled by default. If you want to enable that, run this SQL command locally:

GRANT ALL PRIVILEGES ON *.* TO 'root'@'%' IDENTIFIED BY 'password' WITH GRANT OPTION; FLUSH PRIVILEGES;

Code language: JavaScript (javascript)

And then find the following line and comment it out in your my.cnf file, which usually lives on /etc/mysql/my.cnf on Unix/OSX systems. In some cases the location for the file is /etc/mysql/mysql.conf.d/mysqld.cnf).

Alternatively, 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='user01'; +-------------+-------------+ | Host | User | +-------------+-------------+ | 192.168.0.1 | user01 | +-------------+-------------+ 1 row in set (0.00 sec)

Code language: JavaScript (javascript)

Wrong password provided

This is by far the most common reason for MySQL ERROR 1045 (28000): Access denied for user ‘user’@’localhost’ (using password: YES).

MySQL lists user accounts in the user table of the mysql database. Each MySQL account can be assigned a password, although the user table does not store the cleartext version of the password, but a hash value computed from it.

You cannot read user passwords in plain text from MySQL as the password hash is used for authentication, but if you can get into MySQL command line interface (with root privileges), you can compare what you remember with the hashed value with “PASSWORD” function with the command below.

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)

Code language: JavaScript (javascript)

From the output, we can clearly see that the hashed value for ‘forgotten’ does not match the authentication_string column, which means ‘forgotten’ is the wrong password.

Executing the following query will overwrite the current password with a new one :

mysql> set password for 'nonexistant'@'%' = 'helloworld'; Empty set (0.00 sec)

Code language: PHP (php)

Special characters in the password

If you’re using Bash as your main shell, you should know that not all characters are treated equal in Bash. Some characters are evaluated by Bash to have a non-literal meaning. Instead, these characters carry out a special instruction, or have an alternate meaning; they are called «special characters», or «meta-characters».

In this case, your password contains some of the those special characters which might be mistakenly converted to another form by Bash. To prevent this from happening, wrap your password in single quotes in the command:

[[email protected]]# mysql -u user01 -p'hello$!*&^%$#@!' mysql: [Warning] Using a password on the command line interface can be insecure ... mysql>

Code language: PHP (php)

Regain access to the database

If you’re locked out and need to bypass the authentication mechanisms to regain access to the database, here are simple steps to do so. Please note that we’re using MariaDB to demonstrate the steps.

  1. Stop the instance by running sudo systemctl stop mariadb
  2. Use mysqld_safe to start mysqld server by running the command: mysqld_ safe –user=mysql –skip-grant-tables –skip-networking
  3. Now you can open up a new terminal and access the MySQL server instance with root privileges by running mysql -u root -h localhost .
  4. Please do note that since we’re running grant-skip-tables, any GRANT/CREATE/SET PASSWORD statements won’t work straight away. In order to fix this, run FLUSH PRIVILEGES;.
  5. Run SET PASSWORD FOR 'root'@'localhost' = '[email protected]!' to change the password for root user.
  6. Alternatively, 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’;
  7. Stop the mysqld_safe instance and restart MySQL again from systemctl.
  8. You should be able to login with root from the localhost with the new password and do any other necessary corrective operations with root user.

MySQL users often face an issue called Error 1045 (28000) access denied for user ‘root’@’localhost’ (using password: yes). This usually occurs when you enter an incorrect password or password for your database. Fixing these credentials can resolve this error in no time.

In this article, we will look at the ways to resolve this error.

How to fix “Error 1045 (28000) access denied for user ‘root’@’localhost’ (using password: yes)”?

The error looks something like this — 

mysql -uroot -proot

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

It arises when you perform a fresh installation of MySQL and try to login with a password. The default password of MySQL is blank () (i.e. empty string).

So, you can login to the MySQL server using the same password.

Example  

>mysql -uroot -p

Enter password:

Welcome to the MariaDB monitor.  Commands end with ; or g.

Your MariaDB connection id is 9

Server version: 10.4.11-MariaDB mariadb.org binary distribution

Copyright (c) 2000, 2018, Oracle, MariaDB Corporation Ab and others.

Type ‘help;’ or ‘h’ for help. Type ‘c’ to clear the current input statement.

MariaDB [(none)]>

mysql login

The best practice is to change the password after the new installation.

Set root user password

You must set the root user password after performing the new installation. Here is the code to set it –

Login as user root with blank password

>mysql -u root

mysql> ALTER USER 'root'@'localhost' IDENTIFIED BY 'abc';

Now the new password for root user is abc.

How to fix the Error 1045 (28000)?

Let us look at the ways to fix this problem – 

  1. Enter the correct credentials

The primary method to fix this error is to enter the correct username and password using the following command –

mysql –u username –p       
  1. Ensure the user is correct

Sometimes, the user you might be trying to access does not exist on the MySQL server. You can check if the user exists using the following code-

MariaDB [(none)]> select user from mysql.user where user like '%root%';

+------+

| User |

+------+

| root |

| root |

| root |

+------+

3 rows in set (0.001 sec)  

select user root

If the user does not exist, create it with the desired username.

  1. Enter the correct host name

You might be trying to access the server from a host that is different from the defined host name. You will encounter Error 1045 in this case. You can use this code to view details of the user –

To fix this, you can update the host name for the user using the code below –

mysql> mysql -u root -pabc -h <IP> -P 3306

You might encounter the error in due to the following scenarios –   

Entered wrong password

>mysql -uroot -pssssss

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

Host doesn’t not have permission to connect database

This is a very common error that occurs while connecting to a remote database. While connecting to such a database we need to give access to the HOST IP ADDRESS to connect to it.

This is the IP Address of the source system which connects to the database server.

If access is not given, then run the given command –

CREATE USER ‘dbuser1’@'< Host IP >’ IDENTIFIED VIA mysql_native_password USING ‘***’;GRANT ALL PRIVILEGES ON *.* TO ‘dbuser1’@'< Host IP >’ REQUIRE NONE WITH GRANT OPTION MAX_QUERIES_PER_HOUR 0 MAX_CONNECTIONS_PER_HOUR 0 MAX_UPDATES_PER_HOUR 0 MAX_USER_CONNECTIONS 0;

Conclusion

Apart from all this, make sure the host contains the correct IP address and host name, to avoid the Error 1045 (28000) access denied for user ‘root’@’localhost’ (using password: yes).

WRITE FOR US

Понравилась статья? Поделить с друзьями:
  • Mysql get last error
  • Mysql fatal error что это значит
  • Mysql fatal error allowed memory size
  • Mysql failed error your password does not satisfy the current policy requirements
  • Mysql error что это значит на сайте