- Ошибка access denied for user root localhost
- Что означает access denied for user root localhost?
- Исправляем ошибку access denied for user root localhost
- 1. Подключение с другого хоста
- 2. Неверный пароль root
- Выводы
- Почему не удаётся войти под root MySQL пользователем в PHPMyAdmin?
- Access denied for user ‘root@localhost’ (using password:NO)
- 16 Answers 16
- Access denied for root user in MySQL command-line
- 9 Answers 9
- MySQL Error: : ‘Access denied for user ‘root’@’localhost’
- 20 Answers 20
Ошибка 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 и запустите ее без проверки безопасности, а затем попробуйте снова:
systemctl stop mysqld
mysqld —skip-grant-tables
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 и что делать в таких ситуациях, чтобы решить проблему. Надеюсь, эта информация была полезной для вас. Если у вас остались вопросы, спрашивайте в комментариях!
Почему не удаётся войти под root MySQL пользователем в PHPMyAdmin?
Решение:
mysql -u root -p
use mysql;
update user set plugin=» where User=’root’;
flush privileges;
exit;
systemctl start mariadb
systemctl start mysql
Проверенный рабочий вариант, думаю поможет:
По умолчанию рутовый вход запрещен. Советую создать отдельного пользователя под свои нужды:
(вводить по одной строке)
sudo mysql -u root -p (спросит пароль)
create user ‘пользователь’@localhost identified by ‘пароль’;
grant all privileges on *.* to ‘пользователь’@localhost;
grant grant option on *.* to ‘пользователь’@localhost;
flush privileges;
quit;
Возможно в том, что соотв. записи разрешающей вход — в базе нет. Можно попробовать из под рута запустить mysql-клиент (в консонли). Такой подход работает с MariaDB, с MySQL’ом возможно тоже прокатит.
И посмотреть потом, кому с какого хоста можно заходить. База: mysql, таблица: user. Пример.
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?
But it shows me:
After this I try:
However, it asks for a password which I don’t have.
Update: as Bozho suggested, I did the following:
- I stopped the MySQL Service from Windows services
- Opened CMD
- Changed the location to c:\program files\mysql\bin
Executed the command below
mysqld —defaults-file=»C:\\program files\\mysql\\mysql server 5.1\\my.ini» —init-files=C:\\root.txt
The command ran with a warning about character set which I mentioned below
I write in the command line
mysql -u root -p EnterPassword: 123 // 123 was the password
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
]# mysqld_safe —skip-grant-tables &» and open another terminal to enter «[root
]# mysql -u root» – Liuda Feb 23 ’16 at 20:01
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
Note :- if you are using xampp then , file will be located at
It looks like this:
The error «Access denied for user ‘root@localhost’ (using password:NO)» will be resolved when you set $cfg[‘Servers’][$i][‘AllowNoPassword’] to false
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'»:
- if [‘password’] have a empty quotes like ‘ ‘ then put your password between quotes.
- change the (using password:NO) to (using password:YES)
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 root user in MySQL command-line
I’ve just installed xampp, and am using command line to write mySQL. I am using ‘root’ with no password and can connect to mysql but cannot CREATE DATABASE as I get the error 1044 access denied for user » @ ‘localhost’ . I am logged in as -uroot .
I have privileges in phpMyadmin to do what I want, but, in command line I seem to have no write privileges. I’ve looked at all the other related posts on this topic but to no avail. I cannot GRANT privileges as I have none anyway.
9 Answers 9
Are you logging into MySQL as root? You have to explicitly grant privileges to your «regular» MySQL user account while logged in as MySQL root.
First set up a root account for your MySQL database.
In the terminal type:
To log into MySQL, use this:
To set the privileges manually start the server with the skip-grant-tables option, open mysql client and manually update the mysql.user table and/or the mysql.db tables. This can be a tedious task though so if what you need is an account with all privs I would do the following.
Start the server with the skip-grant-tables option
Start mysql client (without a username/password)
Issue the command
which forces the grant tables to be loaded.
Create a new account with the GRANT command something like this (but replacing username and password with whatever you want to use.
Restart the server in normal mode (without skip-grant-tables) and log in with your newly created account.
MySQL Error: : ‘Access denied for user ‘root’@’localhost’
$ ./mysqladmin -u root -p ‘redacted‘
Enter password:
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
- Open & Edit /etc/my.cnf or /etc/mysql/my.cnf , depending on your distro.
- Add skip-grant-tables under [mysqld]
- Restart Mysql
- You should be able to login to mysql now using the below command mysql -u root -p
- Run mysql> flush privileges;
- Set new password by ALTER USER ‘root’@’localhost’ IDENTIFIED BY ‘NewPassword’;
- Go back to /etc/my.cnf and remove/comment skip-grant-tables
- Restart Mysql
- Now you will be able to login with the new password mysql -u root -p
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.
The relevant part:
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.
Note: If the ALTER USER command doesn’t work, it’s usually indicative of a bigger problem. However, you can try UPDATE . SET to reset the root password instead.
[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 MySQL, use: $ sudo systemctl start mysql
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.