Mysql windows access denied for user root localhost
Если при попытке входа в phpMyAdmin вы видите ошибку:
то данная статья поможет вам разобраться в проблеме и устранить её.
MySQL 5.7 изменила модель безопасности: теперь вход в MySQL под рутом (root) требует sudo (при этом пароль всё равно может быть пустым). Т.е. phpMyAdmin невозможно использовать под пользователем рутом. Подробное объяснение смотрите в статье Аутентификация по паролю и unix_socket в MySQL и MariaDB.
Самым простым (и самым безопасным) решением будет создать нового пользователя и предоставить ему требуемые привилегии.
Но начнём мы с другого решения:
Разрешить пользователю root подключаться к MySQL и MariaDB без sudo
Для получения доступа к базе данных MySQL/MariaDB обычному пользователю без использования sudo привилегий, зайдите в приглашение командной строки MySQL
и запустите следующие команды:
Переключиться на аутентификацию по паролю можно следующим SQL запросом:
Обратите внимание, что вам нужно ввести ПАРОЛЬ.
Затем попробуйте войти в базу данных без sudo, как показано ниже.
Это устаревший метод, он не работает в новых версиях MariaDB, но может по-прежнему работать в MySQL.
Для получения доступа к базе данных MySQL/MariaDB обычному пользователю без использования sudo привилегий, зайдите в приглашение командной строки MySQL
и запустите следующие команды:
Затем перезапустите службу MySQL и попробуйте войти в базу данных без sudo, как показано ниже.
Создание нового пользователя для работы с MySQL через phpMyAdmin
1. Подключитесь к mysql
2. Создайте пользователя для phpMyAdmin
Запустите следующие команды (замените some_pass на желаемый пароль):
Если ваш phpMyAdmin подключается к localhost, то этого должно быть достаточно.
3. Опционально: разрешение удалённых соединений
Помните: разрешение удалённому пользователю иметь все привилегии – это вопрос безопасности, имейте это ввиду, выполняя последующие шаги. Если вы хотите, чтобы этот пользователь имел те же привилегии во время удалённых подключений, дополнительно выполните (замените some_pass на пароль, используемый на Шаге #2):
4. Обновите phpMyAdmin
Используя sudo, отредактируйте файл /etc/dbconfig-common/phpmyadmin.conf обновив значения пользователь/пароль в следующих секциях (замените some_pass на пароль, используемый на шаге #2):
Связанные статьи:
Рекомендуемые статьи:
16 Комментарии
Пипец, почти всю ночь промучился с этим вопросом и чего только не перепробовал, а в итоге… Как вы говорите:
«MySQL 5.7 изменила модель безопасности: теперь вход в MySQL под рутом (root) требует sudo (при этом пароль всё равно может быть пустым). Т.е. phpMyAdmin невозможно использовать под пользователем рутом.»
Нет, вы «врубитесь» еще раз:
«MySQL 5.7 изменила модель безопасности: теперь вход в MySQL под рутом (root) требует sudo«
Потратил столько времени и сил, а Вы описали суть проблемы всего несколькими словами.
Создал нового пользователя ‘phpMyAdmin’ и всё заработало.
Огромное СПАСИБО за помощь!
и запустите следующие команды:
Затем перезапустите службу MySQL и попробуйте войти в базу данных без sudo, как показано ниже.
После этих манипуляций совсем зайти не могу
Access denied for user ‘root@localhost’ (using password:NO)
I’m new to MySQL, I’m trying to run WordPress in my Windows desktop and it needs MySQL.
I install everything with Web Platform Installer which is provided by Microsoft. I never set a root password for MySQL and in the final step of installing WordPress, it asks for a MySQL server password.
What is the default password for root (if there is one) and how to change it?
However, it asks for a password which I don’t have.
Update: as Bozho suggested, I did the following:
Executed the command below
The command ran with a warning about character set which I mentioned below
I write in the command line
The command line shows the following error
Access denied for user ‘root@localhost’ (using password:**YES**)
How do I solve this? I’m waiting to hear from you.
16 Answers 16
You can reset your root password. Have in mind that it is not advisable to use root without password.
for this kind of error; you just have to set new password to the root user as an admin. follow the steps as follows:
Stop the service/daemon of mysql running
Start mysql without any privileges using the following option; This option is used to boot up and do not use the privilege system of MySQL.
At this moment, the terminal will seem to halt. Let that be, and use new terminal for next steps.
enter the mysql command prompt
Fix the permission setting of the root user ;
*if you don`t want any password or rather an empty password
Confirm the results:
Exit the shell and restart mysql in normal mode.
Now you can successfully login as root user with the password you set
1) You can set root password by invoking MySQL console. It is located in
C:\wamp\bin\mysql\mysql5.1.53\bin by default.
Get to the directory and type MySQL. then set the password as follows..
2) You can configure wamp’s phpmyadmin application for root user by editing
It looks like this:
If you priviously changed the password for ‘root@localhost’, then you have to do 2 things to solve the error «Access denided for user ‘root@localhost'»:
This will resolve the error.
Note: phpmyadmin is a separate tool which comes with wamp. It just provide a interface to MySQL. if you change my sql root’s password, then you should change the phpmyadmin configurations. Usually phpmyadmin is configured to root user.
Ошибка access denied for user root localhost
Если вы захотите настроить резервное копирование базы данных на другой сервер, или протестировать соединение с базой данных из другого сервера. И тогда вы можете столкнуться с ошибкой access denied for user root localhost, даже если вы указали верное имя пользователя, базу данных и пароль.
В этой небольшой статье мы рассмотрим почему возникает эта ошибка, а также как ее исправить и подключиться к MySQL из другого сервера через интернет.
Что означает access denied for user root localhost?
Если переводить дословно, то эта ошибка означает что у вас нет доступа к данной базе данных от имени этого пользователя. В примере я использовал пользователя root, но вы можете использовать и другого пользователя. Это может быть вызвано несколькими причинами:
Для безопасности базы данных в mysql была придумана настройка хоста, из которого пользователь может авторизоваться. По умолчанию для пользователей устанавливается разрешение на авторизацию только с localhost. Чтобы разрешить подключение с других хостов, нужно менять настройки. Рассмотрим как это делается с помощью Phpmyadmin и в терминале.
Исправляем ошибку access denied for user root localhost
1. Подключение с другого хоста
Сначала рассмотрим как работать с Phpmyadmin. Это намного проще для начинающих и тех, кто не любит работать в терминале. Откройте Phpmyadmin, авторизуйтесь в программе с правами root и перейдите на вкладку «Учетные записи пользователей»:
Здесь, вы увидите, кроме обычных полей, поле «имя хоста», которое указывает с какого хоста может подключаться пользователь. Если в этом поле написано localhost, значит этот пользователь может авторизоваться только с локальной машины. Также, в этом поле может находиться IP адрес, с которого есть разрешение или символ %, который означает, что пользователь может подключаться с любого IP.
Чтобы изменить права для пользователя, нужно нажать на ссылку «Редактировать привилегии» для него, на открывшейся странице перейдите на вкладку «Информация об учетной записи»:
Затем установите в поле «Имя хоста» значение «Любой хост» чтобы разрешить этому пользователю авторизоваться с любого IP. Если вы хотите разрешить только определенный IP, выберите «Использовать текстовое поле» и укажите нужный адрес или подсеть:
После этого останется нажать кнопку «Вперед» чтобы сохранить настройки. Если вам нужно чтобы был доступ и с локального IP, и с другого, то необходимо создать еще одного пользователя. После этого вы сможете авторизоваться от имени этого пользователя.
Теперь рассмотрим другой способ решить ошибку 1045 access denied for user root localhost, с помощью терминала. Это немного проще, поскольку вам нужно только выполнить несколько команд:
> UPDATE mysql.user SET Host=’%’ WHERE Host=’localhost’ AND User=’имя_пользователя’;
> UPDATE mysql.db SET Host=’%’ WHERE Host=’localhost’ AND User=’имя_пользователя’;
> FLUSH PRIVILEGES;
Уже после этого, вы можете подключаться к серверу баз данных с любого другого компьютера и не получите никаких ошибок. Вместо символа %, можно указать нужный ip или localhost, если ограничение нужно вернуть обратно.
2. Неверный пароль root
Иногда случается, что при установке базы данных пароль для root задается, но вы его не знаете. Поскольку это главный пользователь и если вы не можете войти от его имени, то вы не сможете ничего исправить. Сначала попробуйте авторизоваться от имени root в системе и подключиться к базе без пароля:
Иногда это работает. Если не сработало, остановите службу mysql и запустите ее без проверки безопасности, а затем попробуйте снова:
> USE mysql;
> UPDATE user SET Password=PASSWORD(‘ваш_пароль’) where USER=’root’;
> FLUSH PRIVILEGES;
Еще можно попытаться выдать права над всеми таблицами нашему пользователю, если это необходимо:
> GRANT ALL ON *.* TO ‘root’@’localhost’ WITH GRANT OPTION;
Обратите внимание на хост localhost, если вы хотите чтобы удаленные узлы тоже могли подключаться к этому пользователю, то нужно использовать %. Дальше можно перезапустить базу данных и работать как обычно.
Выводы
Теперь вы знаете как решается mysql access denied for user root localhost и что делать в таких ситуациях, чтобы решить проблему. Надеюсь, эта информация была полезной для вас. Если у вас остались вопросы, спрашивайте в комментариях!
MySQL Error: : ‘Access denied for user ‘root’@’localhost’
mysqladmin: connect to server at ‘localhost’ failed error:
‘Access denied for user ‘root’@’localhost’ (using password: YES)’
How can I fix this?
/.my.cnf file. – e-info128 Mar 22 ’18 at 3:23
20 Answers 20
All solutions I found were much more complex than necessary and none worked for me. Here is the solution that solved my problem. No need to restart mysqld or start it with special privileges.
With a single query we are changing the auth_plugin to mysql_native_password and setting the root password to root (feel free to change it in the query)
Now you should be able to login with root. More information can be found in MySQL documentation or MariaDB documentation
(exit mysql console with Ctrl + D or by typing exit)
None of the above answers helped me with this problem, so here’s the solution I found.
In Ubuntu systems running MySQL 5.7 (and later versions), the root MySQL user is set to authenticate using the auth_socket plugin by default rather than with a password. This allows for some greater security and usability in many cases, but it can also complicate things when you need to allow an external program (e.g., phpMyAdmin) to access the user.
In order to use a password to connect to MySQL as root, you will need to switch its authentication method from auth_socket to mysql_native_password. To do this, open up the MySQL prompt from your terminal:
Next, check which authentication method each of your MySQL user accounts use with the following command:
SELECT user,authentication_string,plugin,host FROM mysql.user;
In this example, you can see that the root user does in fact authenticate using the auth_socket plugin. To configure the root account to authenticate with a password, run the following ALTER USER command. Be sure to change password to a strong password of your choosing, and note that this command will change the root password you set in Step 2:
ALTER USER ‘root’@’localhost’ IDENTIFIED WITH mysql_native_password BY ‘password’;
Then, run FLUSH PRIVILEGES which tells the server to reload the grant tables and put your new changes into effect:
Check the authentication methods employed by each of your users again to confirm that root no longer authenticates using the auth_socket plugin:
SELECT user,authentication_string,plugin,host FROM mysql.user;
You can see in this example output that the root MySQL user now authenticates using a password. Once you confirm this on your own server, you can exit the MySQL shell:
I tried many steps to get this issue corrected. There are so many sources for possible solutions to this issue that is is hard to filter out the sense from the nonsense. I finally found a good solution here:
Step 1: Identify the Database Version
You’ll see some output like this with MySQL:
Or output like this for MariaDB:
Make note of which database and which version you’re running, as you’ll use them later. Next, you need to stop the database so you can access it manually.
Step 2: Stopping the Database Server
To change the root password, you have to shut down the database server beforehand.
You can do that for MySQL with:
And for MariaDB with:
Step 3: Restarting the Database Server Without Permission Checking
If you run MySQL and MariaDB without loading information about user privileges, it will allow you to access the database command line with root privileges without providing a password. This will allow you to gain access to the database without knowing it.
To do this, you need to stop the database from loading the grant tables, which store user privilege information. Because this is a bit of a security risk, you should also skip networking as well to prevent other clients from connecting.
Start the database without loading the grant tables or enabling networking:
The ampersand at the end of this command will make this process run in the background so you can continue to use your terminal.
Now you can connect to the database as the root user, which should not ask for a password.
You’ll immediately see a database shell prompt instead.
MySQL Prompt
MariaDB Prompt
Now that you have root access, you can change the root password.
Step 4: Changing the Root Password
Now we can actually change the root password.
For MySQL 5.7.6 and newer as well as MariaDB 10.1.20 and newer, use the following command:
For MySQL 5.7.5 and older as well as MariaDB 10.1.20 and older, use:
Make sure to replace new_password with your new password of choice.
[IMPORTANT] This is the specific line that fixed my particular issue:
Remember to reload the grant tables after this.
In either case, you should see confirmation that the command has been successfully executed.
The password has been changed, so you can now stop the manual instance of the database server and restart it as it was before.
Step 5: Restart the Database Server Normally
The tutorial goes into some further steps to restart the database, but the only piece I used was this:
For MariaDB, use:
Now you can confirm that the new password has been applied correctly by running:
The command should now prompt for the newly assigned password. Enter it, and you should gain access to the database prompt as expected.
Conclusion
You now have administrative access to the MySQL or MariaDB server restored. Make sure the new root password you choose is strong and secure and keep it in safe place.
‘Access denied for user ‘root’@’localhost’ (using password: NO)’
I’m trying to set the password of the user root but I’m gettin the error below, any idea?
8 Answers 8
password is to be typed literally. It’s a command. You don’t have to substitute password with your actual password.
Login to MySQL console:
To exit the console:
when trying to run this command i got the same error
i simply add a few lines to the code
and pressed the enter key. i then typed my password and hit enter. Linux liked my command as nothing more was displayed
after that hit enter and enter your password
Those are all good answers, but don’t quite touch the deep cause of the problem one most likely has if faced with the OP question. That is, not knowing the ORIGINAL «starting» password created during the installation time.
Now this part from the original installation message may help anyone facing the problem above:
This is basically a more detailed version of a previous answer.
In your Terminal, go to the location of your utility program, mysqladmin
For example, if you were doing local development and using an application like M/W/XAMP, you might go to the directory:
This is where mysqladmin resides.
If you’re not using an application like MAMP, you may also be able to find your local installation of mysql at: /usr/local/mysql
And then if you go to: /usr/local/mysql/bin/
You are in the directory where mysqladmin resides.
Then, to change the password, you will do the following:
At your Terminal prompt enter the exact command below (aka copy and paste) and press enter. The word «password» is part of the command, so don’t be confused and come to the conclusion that you need to replace this word with some password you created previously or want to use in the future. You will have a chance to enter a new password soon enough, but it’s not in this first command that you will do that:
The Terminal will ask you to enter your original or initial password, not a new one yet. From the above image you provided, it looks like you have one already created, so enter it here:
Enter password: oldpassword
New password: newpassword
Confirm new password: newpassword
Reset or restart your Terminal.
In some cases, as with M/W/XAMP, you will have to update this new password in various files in order to get your application running properly again.