I’ve installed MySQL with the following version:
kurt@kurt-ThinkPad:~$ mysql -V
mysql Ver 14.14 Distrib 5.7.15, for Linux (x86_64) using EditLine wrapper
I recall I did not set a password for the root user during setup. However, if I try to simply start it using the mysql command, I get the following error:
kurt@kurt-ThinkPad:~$ mysql
ERROR 1045 (28000): Access denied for user 'kurt'@'localhost' (using password: NO)
Similarly, as a root user,
kurt@kurt-ThinkPad:~$ mysql -u root
ERROR 1698 (28000): Access denied for user 'root'@'localhost'
I tried following the instructions on Resetting the Root Password: Unix and Unix-Like Systems; I made the text file in my home directory, and from there tried to start the MySQL server with the --init-file option. However, I again get a permissions error:
kurt@kurt-ThinkPad:~$ mysqld_safe --init-file=mysql-init &
[1] 18340
kurt@kurt-ThinkPad:~$ /usr/bin/mysqld_safe: 548: /usr/bin/mysqld_safe: cannot create /var/lib/mysql/mysqld_safe.pid: Permission denied
2016-09-20T14:57:04.753720Z mysqld_safe Logging to '/var/log/mysql/error.log'.
cat: /var/run/mysqld/mysqld.pid: Permission denied
rm: cannot remove '/var/run/mysqld/mysqld.pid': Permission denied
2016-09-20T14:57:04.780206Z mysqld_safe Fatal error: Can't remove the pid file:
/var/run/mysqld/mysqld.pid
Please remove it manually and start /usr/bin/mysqld_safe again;
mysqld daemon not started
/usr/bin/mysqld_safe: 135: /usr/bin/mysqld_safe: cannot create /var/log/mysql/error.log: Permission denied
rm: cannot remove '/var/lib/mysql/mysqld_safe.pid': Permission denied
I have read about a similar error in Cant connect to Mysql server ; Can’t create/write the pid file, where the proposed solution is to assign the MySQL user to the /var/run/mysqld directory. However, if I try this I get «Operation not permitted»:
kurt@kurt-ThinkPad:~$ chown mysql:mysql /var/run/mysqld
chown: changing ownership of '/var/run/mysqld': Operation not permitted
Any ideas on how to get MySQL to work?
I’ve installed MySQL with the following version:
kurt@kurt-ThinkPad:~$ mysql -V
mysql Ver 14.14 Distrib 5.7.15, for Linux (x86_64) using EditLine wrapper
I recall I did not set a password for the root user during setup. However, if I try to simply start it using the mysql command, I get the following error:
kurt@kurt-ThinkPad:~$ mysql
ERROR 1045 (28000): Access denied for user 'kurt'@'localhost' (using password: NO)
Similarly, as a root user,
kurt@kurt-ThinkPad:~$ mysql -u root
ERROR 1698 (28000): Access denied for user 'root'@'localhost'
I tried following the instructions on Resetting the Root Password: Unix and Unix-Like Systems; I made the text file in my home directory, and from there tried to start the MySQL server with the --init-file option. However, I again get a permissions error:
kurt@kurt-ThinkPad:~$ mysqld_safe --init-file=mysql-init &
[1] 18340
kurt@kurt-ThinkPad:~$ /usr/bin/mysqld_safe: 548: /usr/bin/mysqld_safe: cannot create /var/lib/mysql/mysqld_safe.pid: Permission denied
2016-09-20T14:57:04.753720Z mysqld_safe Logging to '/var/log/mysql/error.log'.
cat: /var/run/mysqld/mysqld.pid: Permission denied
rm: cannot remove '/var/run/mysqld/mysqld.pid': Permission denied
2016-09-20T14:57:04.780206Z mysqld_safe Fatal error: Can't remove the pid file:
/var/run/mysqld/mysqld.pid
Please remove it manually and start /usr/bin/mysqld_safe again;
mysqld daemon not started
/usr/bin/mysqld_safe: 135: /usr/bin/mysqld_safe: cannot create /var/log/mysql/error.log: Permission denied
rm: cannot remove '/var/lib/mysql/mysqld_safe.pid': Permission denied
I have read about a similar error in Cant connect to Mysql server ; Can’t create/write the pid file, where the proposed solution is to assign the MySQL user to the /var/run/mysqld directory. However, if I try this I get «Operation not permitted»:
kurt@kurt-ThinkPad:~$ chown mysql:mysql /var/run/mysqld
chown: changing ownership of '/var/run/mysqld': Operation not permitted
Any ideas on how to get MySQL to work?
I’m setting up a new server and keep running into this problem.
When I try to log into the MySQL database with the root user, I get the error:
ERROR 1698 (28000): Access denied for user ‘root’@’localhost’
It doesn’t matter if I connect through the terminal (SSH), through phpMyAdmin or a MySQL client, e.g., Navicat. They all fail.
I looked in the mysql.user table and get the following:
+------------------+-------------------+
| user | host |
+------------------+-------------------+
| root | % |
| root | 127.0.0.1 |
| amavisd | localhost |
| debian-sys-maint | localhost |
| iredadmin | localhost |
| iredapd | localhost |
| mysql.sys | localhost |
| phpmyadmin | localhost |
| root | localhost |
| roundcube | localhost |
| vmail | localhost |
| vmailadmin | localhost |
| amavisd | test4.folkmann.it |
| iredadmin | test4.folkmann.it |
| iredapd | test4.folkmann.it |
| roundcube | test4.folkmann.it |
| vmail | test4.folkmann.it |
| vmailadmin | test4.folkmann.it |
+------------------+-------------------+
As you can see, user root should have access.
The Server is quite simple, as I have tried to troubleshoot this for a while now.
It’s running Ubuntu 16.04.1 LTS (Xenial Xerus) with Apache, MySQL and PHP, so that it can host websites, and iRedMail 0.9.5-1, so that it can host mail.
Log into the MySQL database works fine before I installed iRedMail. I also tried just installing iRedMail, but then root also doesn’t work.
How can I fix my MySQL login problem or how can I install iRedMail over an existing MySQL install? And yes, I tried the Installation Tips and I can’t find those variables in the configuration files.
Jeff Holt
2,9003 gold badges23 silver badges29 bronze badges
asked Sep 1, 2016 at 22:06
3
On some systems, like Ubuntu, MySQL is using the Unix auth_socket plugin by default.
Basically it means that: db_users using it, will be «authenticated» by the system user credentials. You can see if your root user is set up like this by doing the following:
sudo mysql -u root # I had to use "sudo" since it was a new installation
mysql> USE mysql;
mysql> SELECT User, Host, plugin FROM mysql.user;
+------------------+-----------------------+
| User | plugin |
+------------------+-----------------------+
| root | auth_socket |
| mysql.sys | mysql_native_password |
| debian-sys-maint | mysql_native_password |
+------------------+-----------------------+
As you can see in the query, the root user is using the auth_socket plugin.
There are two ways to solve this:
- You can set the root user to use the
mysql_native_passwordplugin - You can create a new
db_userwith yousystem_user(recommended)
Option 1:
sudo mysql -u root # I had to use "sudo" since it was a new installation
mysql> USE mysql;
mysql> UPDATE user SET plugin='mysql_native_password' WHERE User='root';
mysql> FLUSH PRIVILEGES;
mysql> exit;
sudo service mysql restart
Option 2: (replace YOUR_SYSTEM_USER with the username you have)
sudo mysql -u root # I had to use "sudo" since it was a new installation
mysql> USE mysql;
mysql> CREATE USER 'YOUR_SYSTEM_USER'@'localhost' IDENTIFIED BY 'YOUR_PASSWD';
mysql> GRANT ALL PRIVILEGES ON *.* TO 'YOUR_SYSTEM_USER'@'localhost';
mysql> UPDATE user SET plugin='auth_socket' WHERE User='YOUR_SYSTEM_USER';
mysql> FLUSH PRIVILEGES;
mysql> exit;
sudo service mysql restart
Remember that if you use option #2 you’ll have to connect to MySQL as your system username (mysql -u YOUR_SYSTEM_USER).
Note: On some systems (e.g., Debian 9 (Stretch)) the ‘auth_socket’ plugin is called ‘unix_socket’, so the corresponding SQL command should be: UPDATE user SET plugin='unix_socket' WHERE User='YOUR_SYSTEM_USER';
From andy’s comment it seems that MySQL 8.x.x updated/replaced the auth_socket for caching_sha2_password. I don’t have a system setup with MySQL 8.x.x to test this. However, the steps above should help you to understand the issue. Here’s the reply:
One change as of MySQL 8.0.4 is that the new default authentication plugin is ‘caching_sha2_password’. The new ‘YOUR_SYSTEM_USER’ will have this authentication plugin and you can log in from the Bash shell now with «mysql -u YOUR_SYSTEM_USER -p» and provide the password for this user on the prompt. There isn’t any need for the «UPDATE user SET plugin» step.
For the 8.0.4 default authentication plugin update, see MySQL 8.0.4: New Default Authentication Plugin: caching_sha2_password.
answered Mar 12, 2017 at 1:17
zetacuzetacu
16.7k1 gold badge18 silver badges26 bronze badges
25
A new version of MySQL does it this way
In the new MySQL client, if the password is left empty while installing then, it is based on the auth_socket plugin.
The correct way is to log in to MySQL with the sudo privilege.
sudo mysql -u root -p
And then updating the password using:
ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY 'new-password';
Once this is done, stop and start the MySQL server.
sudo service mysql stop
sudo service mysql start
For complete details, you can refer to this link.
answered Sep 14, 2018 at 16:17
NandeshNandesh
4,3372 gold badges20 silver badges26 bronze badges
8
No need of sudo
The database is initialised with 2 all-privilege accounts: the first one is «root» which is inaccessible and the second one with your user name (check with command whoami).
To enable access to root account, you need to login with your user name
mysql -u $(whoami)
and manually change password for root
use mysql;
set password for 'root'@'localhost' = password('YOUR_ROOT_PASSWORD_HERE');
flush privileges;
quit
Login as ‘root’
mysql -u root -p
answered Jan 10, 2020 at 18:31
4
I was having this issue on an Debian 8 (Jessie) VM that I was interacting with through PuTTY on my Windows 10 desktop.
I tried the various suggestions on here, but nothing quite worked and I am running MariaDB on the Debian host. In the end I found that I couldn’t start the database server in safe mode, but I didn’t need to and the following commands actually worked for me, i.e., allowing a newly created MySQL user to log into the MySQL/MariaDB server:
sudo service mysql restart
sudo mysql # Logs in automatically into MariaDB
use mysql;
update user set plugin='' where user='your_user_name';
flush privileges;
exit;
sudo service mysql restart # Restarts the MySQL service
If the above doesn’t quite work for you, follow the steps outlined in zetacu’s post, and then follow my steps.
Now you should be able to use a remote terminal client and securely log into MySQL using the command:
mysql -u your_user_name -p
*Type in the password when prompted
answered Nov 11, 2017 at 14:03
TrevorTrevor
1,5311 gold badge19 silver badges27 bronze badges
2
Step 1. sudo mysql -u root -p
Step 2. USE mysql;
Step 3. ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY 'admin';
Here ‘admin’ is your new password, but you can change it.
Step 4. exit
You are done.
answered Dec 1, 2018 at 11:04
After hours of struggling without any solution here, this worked for me. I found a YouTube video where it says the password column is now called authentication_string.
So I was able to change my password as follows:
First get into the MySQL client from the terminal:
sudo mysql
Then inside mysql, type whatever after mysql>:
mysql> use mysql
mysql> update user set authentication_string=PASSWORD("mypass") where user='root';
mysql> flush privileges;
mysql> quit;
At this point you are out of the MySQL client, back to your normal terminal place. You need to restart the MySQL client for this to take effect. For that type, the following:
sudo service mysql restart
Refer to this video link for a better understanding.
answered Jan 29, 2020 at 17:09
I would suggest to remove the MySQL connection —
This is for MySQL version 5.5. If your version is different, please change the first line accordingly.
sudo apt-get purge mysql-server mysql-client mysql-common mysql-server-core-5.5 mysql-client-core-5.5
sudo rm -rf /etc/mysql /var/lib/mysql
sudo apt-get autoremove
sudo apt-get autoclean
And install again, but this time set a root password yourself.
This will save a lot of effort.
sudo apt-get update
sudo apt-get install mysql-server
answered Mar 10, 2017 at 12:25
Eminem347Eminem347
3774 silver badges11 bronze badges
4
I found my solution after hours of research here.
Stop MySQL
sudo service mysql stop
Make MySQL service directory.
sudo mkdir /var/run/mysqld
Give MySQL user permission to write to the service directory.
sudo chown mysql: /var/run/mysqld
Start MySQL manually, without permission checks or networking.
sudo mysqld_safe --skip-grant-tables --skip-networking &
Log in without a password.
mysql -uroot mysql
Update password
UPDATE mysql.user SET authentication_string=PASSWORD('YOURNEWPASSWORD'), plugin='mysql_native_password' WHERE User='root' AND Host='%';
EXIT;
Turn off MySQL.
sudo mysqladmin -S /var/run/mysqld/mysqld.sock shutdown
Start the MySQL service normally.
sudo service mysql start
answered Sep 3, 2019 at 6:41
Sanjun DevSanjun Dev
5188 silver badges20 bronze badges
0
For the first
sudo mysql -u root -p
SHOW VARIABLES LIKE 'validate_password%';
we will see something like this:
+--------------------------------------+--------+
| Variable_name | Value |
+--------------------------------------+--------+
| validate_password.check_user_name | ON |
| validate_password.dictionary_file | |
| validate_password.length | 8 |
| validate_password.mixed_case_count | 1 |
| validate_password.number_count | 1 |
| validate_password.policy | MEDIUM |
| validate_password.special_char_count | 1 |
+--------------------------------------+--------+
We need to change these rows:
- validate_password.length
- validate_password.number_count
- validate_password.policy
- validate_password.special_char_count
SET GLOBAL validate_password.policy=LOW;
SET GLOBAL validate_password.length=4;
SET GLOBAL validate_password.number_count=0;
SET GLOBAL validate_password.special_char_count=0;
SHOW VARIABLES LIKE 'validate_password%';
We will see:
+--------------------------------------+-------+
| Variable_name | Value |
+--------------------------------------+-------+
| validate_password.check_user_name | ON |
| validate_password.dictionary_file | |
| validate_password.length | 4 |
| validate_password.mixed_case_count | 1 |
| validate_password.number_count | 0 |
| validate_password.policy | LOW |
| validate_password.special_char_count | 0 |
+--------------------------------------+-------+
Now exit from the MySQL client:
exit;
sudo mysql -u root -p
And now you can write your password, four or more only letters.
ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY 'new-password';
exit;
sudo mysql -u root -p
Your new password is in the database for user ‘root’;
answered Jan 14, 2021 at 20:16
TaronTaron
1691 silver badge12 bronze badges
I also faced the same issue for the first time.
Now it is fixed:
First, you copy the /etc/mysql/mysql.conf.d/mysqld.cnf file and paste in to /etc/mysql/my.cnf.
You can do it by the command:
sudo cp /etc/mysql/mysql.conf.d/mysqld.cnf /etc/mysql/my.cnf
Now let’s reset the password:
Use the following commands in your terminal:
sudo service mysql stop
sudo service mysql start
sudo mysql -u root
Now you are inside the MySQL console.
Then let’s write some queries to reset our root password:
USE mysql
update mysql.user set authentication_string=password('newpass') where user='root' and Host ='localhost';
update user set plugin="mysql_native_password";
flush privileges;
quit
Now we can clean /etc/mysql/my.cng.
Open the above file in your editor and remove the whole lines inside the file.
After that let’s restart MySQL:
sudo mysql service restart
Now let’s use MySQL with the newly created password:
sudo mysql -u root -p
Finally enter your newly created password.
answered Jul 18, 2019 at 11:42
1
In my case,
mysql -u root -p
Enter password:
ERROR 1698 (28000): Access denied for user 'root'@'localhost'
I am sure my password was correct. Otherwise, the error code would be ERROR 1045 (28000): Access denied for user
So I relogin using sudo,
sudo mysql -u root -p
This time it worked for me. See the documentation.
And then change the root password,
mysql> alter user 'root'@'%' identified with mysql_native_password by 'me123';
Query OK, 0 rows affected (0.14 sec)
mysql>
Then restart the server using sudo /etc/init.d/mysql restart.
answered Dec 3, 2019 at 13:16
This worked for me:
mysql --user=root mysql
CREATE USER 'some_user'@'%' IDENTIFIED BY 'some_pass';
GRANT ALL PRIVILEGES ON *.* TO 'some_user'@'%' WITH GRANT OPTION;
FLUSH PRIVILEGES;
answered Dec 30, 2018 at 21:19
DoradDorad
3,3862 gold badges43 silver badges68 bronze badges
2
This works for me with MySQL version 8.0.26 and Ubuntu 20.04 (Focal Fossa).
sudo mysql -u root
mysql> USE mysql;
mysql> SELECT User, Host, plugin FROM mysql.user;
+------------------+-----------+-----------------------+
| User | Host | plugin |
+------------------+-----------+-----------------------+
| debian-sys-maint | localhost | caching_sha2_password |
| mysql.infoschema | localhost | caching_sha2_password |
| mysql.session | localhost | caching_sha2_password |
| mysql.sys | localhost | caching_sha2_password |
| root | localhost | auth_socket |
+------------------+-----------+-----------------------+
mysql> UPDATE user SET
plugin='caching_sha2_password' WHERE User='root';
mysql> ALTER USER 'root'@'localhost' IDENTIFIED WITH caching_sha2_password BY 'you_mysql_password';
mysql> FLUSH PRIVILEGES;
mysql> exit;
sudo service mysql restart
answered Sep 3, 2021 at 9:48
WhileWhile
611 bronze badge
1
OS: Ubuntu 18.04 (Bionic Beaver)
MySQL: 5.7
-
Add the
skip-grant-tablesto the end of file mysqld.cnf -
Copy the my.cnf file
sudo cp /etc/mysql/mysql.conf.d/mysqld.cnf /etc/mysql/my.cnf -
Reset the password
(base) ➜ ~ sudo service mysql stop (base) ➜ ~ sudo service mysql start (base) ➜ ~ mysql -uroot Welcome to the MySQL monitor. Commands end with ; or g. Your MySQL connection id is 2 Server version: 5.7.25-0ubuntu0.18.04.2 (Ubuntu) Copyright (c) 2000, 2019, 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 owners. Type 'help;' or 'h' for help. Type 'c' to clear the current input statement. mysql> use mysql Reading table information for completion of table and column names You can turn off this feature to get a quicker startup with -A Database changed, 3 warnings mysql> update mysql.user set authentication_string=password('newpass') where user='root' and Host ='localhost'; Query OK, 1 row affected, 1 warning (0.00 sec) Rows matched: 1 Changed: 1 Warnings: 1 mysql> update user set plugin="mysql_native_password"; Query OK, 0 rows affected (0.00 sec) Rows matched: 4 Changed: 0 Warnings: 0 mysql> flush privileges; Query OK, 0 rows affected (0.00 sec) mysql> quit Bye -
Remove the
skip-grant-tablesfrom my.cnf(base) ➜ ~ sudo emacs /etc/mysql/mysql.conf.d/mysqld.cnf (base) ➜ ~ sudo emacs /etc/mysql/my.cnf (base) ➜ ~ sudo service mysql restart -
Open the MySQL client
(base) ➜ ~ mysql -uroot -ppassword mysql: [Warning] Using a password on the command line interface can be insecure. Welcome to the MySQL monitor. Commands end with ; or g. Your MySQL connection id is 3 Server version: 5.7.25-0ubuntu0.18.04.2 (Ubuntu) Copyright (c) 2000, 2019, 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 owners. Type 'help;' or 'h' for help. Type 'c' to clear the current input statement. mysql> -
Check the password policy
mysql> select @@validate_password_policy; +----------------------------+ | @@validate_password_policy | +----------------------------+ | MEDIUM | +----------------------------+ 1 row in set (0.00 sec) mysql> SHOW VARIABLES LIKE 'validate_password%'; +--------------------------------------+--------+ | Variable_name | Value | +--------------------------------------+--------+ | validate_password_dictionary_file | | | validate_password_length | 8 | | validate_password_mixed_case_count | 1 | | validate_password_number_count | 1 | | validate_password_policy | MEDIUM | | validate_password_special_char_count | 1 | +--------------------------------------+--------+ 6 rows in set (0.08 sec)! -
Change the configuration of the
validate_passwordmysql> set global validate_password_policy=0; Query OK, 0 rows affected (0.05 sec) mysql> set global validate_password_mixed_case_count=0; Query OK, 0 rows affected (0.00 sec) mysql> set global validate_password_number_count=3; Query OK, 0 rows affected (0.00 sec) mysql> set global validate_password_special_char_count=0; Query OK, 0 rows affected (0.00 sec) mysql> set global validate_password_length=3; Query OK, 0 rows affected (0.00 sec) mysql> SHOW VARIABLES LIKE 'validate_password%'; +--------------------------------------+-------+ | Variable_name | Value | +--------------------------------------+-------+ | validate_password_dictionary_file | | | validate_password_length | 3 | | validate_password_mixed_case_count | 0 | | validate_password_number_count | 3 | | validate_password_policy | LOW | | validate_password_special_char_count | 0 | +--------------------------------------+-------+ 6 rows in set (0.00 sec)
Note
You should know that you error caused by what? validate_password_policy?
You should have decided to reset the your password to fill the policy or change the policy.
answered Mar 23, 2019 at 4:36
iamcxliamcxl
6871 gold badge7 silver badges15 bronze badges
First step: go to file /etc/phpmyadmin/config.inc.php, and then uncomment lines where you find «AllowNoPassword».
Second step: log in to your MySQL default account
mysql -u root -p
use mysql;
update user set plugin="" where user='root';
flush privileges;
And that’s all!
answered Apr 17, 2018 at 20:00
2
This worked for me on mysql Ver 15.1:
$ sudo mysql
MariaDB [mysql]> use mysql;
MariaDB [mysql]> set password for 'root'@'localhost' = password('YOUR_ROOT_PASSWORD_HERE');
MariaDB [mysql]> flush privileges;
MariaDB [mysql]> quit
Login as ‘root’
mysql -u root -p
Credits to Raoul HATTERER
answered Oct 26, 2022 at 9:26
BlackBlack
17.1k36 gold badges150 silver badges256 bronze badges
the answer given by @zetacu and @peter is very accurate but only part of it worked for me. Adding this here for users who are using
mysql Ver 8.0.30-0ubuntu0.20.04.2 for Linux on x86_64 ((Ubuntu))
So, my user table looked like this:
mysql> SELECT User,Host,plugin FROM mysql.user;
+------------------+-----------+-----------------------+
| User | Host | plugin |
+------------------+-----------+-----------------------+
| debian-sys-maint | localhost | caching_sha2_password |
| mysql.infoschema | localhost | caching_sha2_password |
| mysql.session | localhost | caching_sha2_password |
| mysql.sys | localhost | caching_sha2_password |
| pk | localhost | auth_socket |
| root | localhost | auth_socket |
+------------------+-----------+-----------------------+
6 rows in set (0.00 sec)
So, first I followed the second(recommended) option of replacing YOUR_SYSTEM_USER with the username you have. So, I created a new user with same approach but nothing worked.
Then I tried the first approach to set root user to use my_native_password plugin:
sudo mysql -u root
mysql> USE MySQL;
mysql> UPDATE user SET plugin='mysql_native_password' WHERE
User='root';
mysql> FLUSH PRIVILEGES;
mysql> exit;
sudo service mysql restart
AND IT WORKED!!! SO, just create a new user and make it use my_native_password plugin.
answered Oct 27, 2022 at 12:37
For those installing the latest MariaDB on macOS and following this tutorial in MariaDB’s documentation, run:
sudo mariadb-secure-installation
instead of just the mariadb-secure-installation command given. Otherwise, no luck, despite the erroneous prompt:
In order to log into MariaDB to secure it, we'll need the current
password for the root user. If you've just installed MariaDB, and
haven't set the root password yet, you should just press enter here.
Enter current password for root (enter for none):
ERROR 1698 (28000): Access denied for user 'root'@'localhost'
Enter current password for root (enter for none):
ERROR 1698 (28000): Access denied for user 'root'@'localhost'
Enter current password for root (enter for none):
Aborting!
answered Jan 28, 2022 at 22:25
Geyser14Geyser14
1,2953 gold badges14 silver badges32 bronze badges
This has happened to me as well. The problem is with the MySQL repository that comes already with the Linux distribution. So when you simply do:
sudo apt install mysql-server
It installs MySQL from their default repository which gives this problem. So to overcome that you need to uninstall that installed MySQL:
sudo apt remove mysql* --purge --auto-remove
Then download the MySQL repository from official MySQL website MySQL APT repository.
Follow their documentation on how to add a repository and
install it. This gives no issue.
Also as answered by zetacu, you can verify that the MySQL root user now indeed uses the mysql_native_password plugin.
answered Jan 13, 2019 at 11:03
sudipsudip
1431 gold badge1 silver badge9 bronze badges
I have done the following steps to get rid of this issue.
Log in into the MySQL in your machine using (sudo mysql -p -u root) and hit the following queries.
-
CREATE USER ‘jack’@’localhost’ IDENTIFIED WITH mysql_native_password BY ‘<>’;
-
GRANT ALL PRIVILEGES ON . TO ‘jack’@’localhost’;
-
SELECT user,plugin,host FROM mysql.user WHERE user = ‘root’;
+------+-------------+-----------+ | user | plugin | host | +------+-------------+-----------+ | root | auth_socket | localhost | +------+-------------+-----------+ -
ALTER USER ‘root’@’localhost’ IDENTIFIED WITH mysql_native_password BY ‘<>’;
-
FLUSH PRIVILEGES;
Please try it once if you are still getting the error. I hope this code will help you a lot!!
answered Dec 31, 2020 at 5:20
For anyone that tried the solution here and nothing works, make sure you are using the correct command, sudo sudo mysql -u root -p and not mysql mysql -u root -p.
You’ll need to enter two passwords, the one of the current user and the root one.
answered May 21, 2021 at 1:47
1
You want to access MySQL with root user but you’re not providing root’s correct password.
If you need to set a new password for root, MySQL’s site has great documentation on how to do it: B.3.3.2 How to Reset the Root Password
I’ll not show the process in here, because MySQL’s documentation on the above link is clear and concise.
answered Sep 2, 2016 at 0:36
3
Most of the time, this error comes because the “root” account of MySQL is set only to allow Unix Socket based authentication. So, enter the following commands using a terminal to change its authentication plugin either to Caching SHA-2 or Native authentication.
Login to MySQL CLI.
sudo mysql
Enter fullscreen mode
Exit fullscreen mode
First, we need to make sure that the root account uses the auth_socket plugin, for that run the following command.
SELECT host,user,authentication_string,plugin FROM mysql.user;
Enter fullscreen mode
Exit fullscreen mode
It should display something similar to this. Look at the plugin used by the root account, it should be auth_socket.
+-----------+------------------+------------------------------------------------------------------------+-----------------------+
| host | user | authentication_string | plugin |
+-----------+------------------+------------------------------------------------------------------------+-----------------------+
| localhost | debian-sys-maint | $A$005$:ddQ82h3oaB1+gf0FF.Uq5Gkaj3cVHbEWusZIIpJEBigM17KwLcFDcv6Z2zJ20 | caching_sha2_password |
| localhost | mysql.infoschema | $A$005$THISISACOMBINATIONOFINVALIDSALTANDPASSWORDTHATMUSTNEVERBRBEUSED | caching_sha2_password |
| localhost | mysql.session | $A$005$THISISACOMBINATIONOFINVALIDSALTANDPASSWORDTHATMUSTNEVERBRBEUSED | caching_sha2_password |
| localhost | mysql.sys | $A$005$THISISACOMBINATIONOFINVALIDSALTANDPASSWORDTHATMUSTNEVERBRBEUSED | caching_sha2_password |
| localhost | phpmyadmin | $A$005$7.sK5b2|eI*r%2pnFO7wtVj57sqt54wR8FA3gsj6LEvvahn64BgPSD6Y5IyjzX8 | caching_sha2_password |
| localhost | root | | auth_socket |
+-----------+------------------+------------------------------------------------------------------------+-----------------------+
Enter fullscreen mode
Exit fullscreen mode
Then run the following command to change the authentication plugin to Caching SHA-2 authentication.
ALTER USER 'root'@'localhost' IDENTIFIED WITH caching_sha2_password BY '';
Enter fullscreen mode
Exit fullscreen mode
Alternatively, you can use Native authentication as well, but use either.
ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY '';
Enter fullscreen mode
Exit fullscreen mode
Run this command to reload and apply changes.
FLUSH PRIVILEGES;
Enter fullscreen mode
Exit fullscreen mode
Again confirm whether changes have been successfully applied or not by running this command.
SELECT host,user,authentication_string,plugin FROM mysql.user;
Enter fullscreen mode
Exit fullscreen mode
You should be able to see something similar to this,
+-----------+------------------+------------------------------------------------------------------------+-----------------------+
| host | user | authentication_string | plugin |
+-----------+------------------+------------------------------------------------------------------------+-----------------------+
| localhost | debian-sys-maint | $A$005$:ddQ82h3oaB1+gf0FF.Uq5Gkaj3cVHbEWusZIIpJEBigM17KwLcFDcv6Z2zJ20 | caching_sha2_password |
| localhost | mysql.infoschema | $A$005$THISISACOMBINATIONOFINVALIDSALTANDPASSWORDTHATMUSTNEVERBRBEUSED | caching_sha2_password |
| localhost | mysql.session | $A$005$THISISACOMBINATIONOFINVALIDSALTANDPASSWORDTHATMUSTNEVERBRBEUSED | caching_sha2_password |
| localhost | mysql.sys | $A$005$THISISACOMBINATIONOFINVALIDSALTANDPASSWORDTHATMUSTNEVERBRBEUSED | caching_sha2_password |
| localhost | phpmyadmin | $A$005$7.sK5b2|eI*r%2pnFO7wtVj57sqt54wR8FA3gsj6LEvvahn64BgPSD6Y5IyjzX8 | caching_sha2_password |
| localhost | root | | caching_sha2_password |
+-----------+------------------+------------------------------------------------------------------------+-----------------------+
Enter fullscreen mode
Exit fullscreen mode
Now you can exit from MySQL CLI.
exit
Enter fullscreen mode
Exit fullscreen mode
Now you should be able to log in to the MySQL server with the ‘root’ account, the password will be blank. If you need to set a password, add it like this.
ALTER USER 'root'@'localhost' IDENTIFIED WITH caching_sha2_password BY 'super-secret-password';
Enter fullscreen mode
Exit fullscreen mode
An Animated Guide to Node.js Event Lop
Node.js doesn’t stop from running other operations because of Libuv, a C++ library responsible for the event loop and asynchronously handling tasks such as network requests, DNS resolution, file system operations, data encryption, etc.
What happens under the hood when Node.js works on tasks such as database queries? We will explore it by following this piece of code step by step.
Я только что установил Ubuntu 16.04 и установил на нем веб-сервер. Все работает хорошо, но я не могу получить доступ к базе данных. Я пробовал все в Интернете, также здесь, но ничего не работает… даже если я создаю нового пользователя и даю все привилегии, я не могу создать базу данных 
SQLSTATE[HY000] [1698] Access denied for user 'root'@'localhost'
Когда я пытаюсь войти в терминал, он работает, но в PHP и phpmyadmin нет. Пожалуйста помоги.
Код PHP:
protected $host = '127.0.0.1';
protected $db = 'dbname';
protected $name = 'root';
protected $pass = 'root';
protected $conn;
private static $settings = array(
PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8'
);
public function __construct() {
try {
$this->conn = new PDO("mysql:host=$this->host;dbname=$this->db", $this->name, $this->pass, self::$settings);
} catch (PDOException $e) {
echo $e->getMessage();
}
}
26 апр. 2016, в 14:05
Поделиться
Источник
7 ответов
Оказывается, вы больше не можете использовать пользователя root в 5.7, не становясь sudoer. Это означает, что вы больше не можете запускать mysql -u root sudo mysql -u root вместо этого sudo mysql -u root.
Это также означает, что он больше не будет работать, если вы используете пользователя root в графическом интерфейсе (или предположительно любом приложении без командной строки). Чтобы он работал, вам придется создать нового пользователя с необходимыми привилегиями и использовать его вместо этого.
См. Этот ответ для получения более подробной информации.
Andris
28 апр. 2016, в 10:37
Поделиться
Эти шаги работали для меня в нескольких системах с использованием Ubuntu 16.04, Apache 2.4, MariaDB, PDO
-
войдите в MYSQL как root
mysql -u root -
Предоставьте привилегии. Для нового пользователя выполните:
CREATE USER 'newuser'@'localhost' IDENTIFIED BY 'password'; GRANT ALL PRIVILEGES ON *.* TO 'newuser'@'localhost'; FLUSH PRIVILEGES; -
привязать ко всем адресам:
Самый простой способ — прокомментировать строку в файле /etc/mysql/mariadb.conf.d/50-server.cnf или/etc/mysql/mysql.conf.d/mysqld.cnf, в зависимости от того, какая система вы Бег:
#bind-address = 127.0.0.1 -
выйти из mysql и перезапустить mysql
exit service mysql restart
По умолчанию он привязывается только к localhost, но если вы прокомментируете строку, она связывается со всеми найденными интерфейсами. Комментирование строки эквивалентно bind-адресу = *.
Чтобы проверить привязку службы mysql, выполните от root:
netstat -tupan | grep mysql
leopold
02 авг. 2016, в 14:35
Поделиться
Может быть, немного поздно, но я нашел этот ответ, просматривая интернет. Это может помочь другим с той же проблемой.
$sudo mysql -u root
[mysql] use mysql;
[mysql] update user set plugin='' where User='root';
[mysql] flush privileges;
[mysql] q
Теперь вы можете войти в систему как root в phpmyadmin.
(Найдено здесь.)
Matematikisto
17 июль 2017, в 11:00
Поделиться
MySQL делает разницу между «localhost» и «127.0.0.1».
Возможно, что «root» @»localhost» не разрешен, потому что в таблице пользователя есть запись, которая разрешает вход root только с 127.0.0.1.
Это также может объяснить, почему некоторые приложения на вашем сервере могут подключаться к базе данных, а некоторые из-за отсутствия разных способов подключения к базе данных. И вы в настоящее время не разрешаете это через «localhost».
adjepatatje
26 апр. 2016, в 13:34
Поделиться
Чтобы создать пользователя для phpMyAdmin:
sudo mysql -p -u root
Теперь вы можете добавить нового пользователя MySQL с выбранным вами именем пользователя.
CREATE USER 'USERNAME'@'%' IDENTIFIED BY 'PASSWORD';
И, наконец, предоставьте привилегии суперпользователя только что созданному пользователю.
GRANT ALL PRIVILEGES ON *.* TO 'USERNAME'@'%' WITH GRANT OPTION;
По любому вопросу, пожалуйста, оставьте комментарий
Djamal Dagirov
15 апр. 2019, в 15:02
Поделиться
С mysql Ver 14.14. Распространяйте 5.7.22. Инструкция обновления теперь:
update user set authentication_string=password('1111') where user='root';
sebastian.roibu
04 июль 2018, в 20:45
Поделиться
Пользователи для mysql и для сервера — это две разные вещи, посмотрите, как добавить пользователя в базу данных и войти с этими учетными данными
Autor69
26 апр. 2016, в 13:49
Поделиться
Ещё вопросы
- 1Группировка массивов и получение последнего и первого массива для каждой группы
- 0Наложение на window.history.go (-1)
- 0как сохранить данные в базе данных с помощью jquery
- 0Как выровнять текст внутри <span> после <button>
- 1Android — сохранение состояния активности при запуске новой активности
- 1Обнаружение исключений в родительском классе
- 1Java статическая переменная экземпляра перезаписана в другом экземпляре?
- 0Высота CSS 100% в автоматическом режиме Brother DIV не работает в Chrome
- 0Почему двусторонняя привязка не работает в некоторых ситуациях?
- 1преобразовать массив numpy из объекта dtype в float
- 1Будет ли HBase сканировать строки, которые не содержат семейств, которые я хочу вернуть
- 0JQuery UI — DatePicker — установка второго на основе выбора из первого
- 1Используйте функцию связывания дважды [дубликата]
- 1Простой JavaScript — ScrollIntoView внутри Div
- 1Полноэкранный предварительный просмотр после захвата изображения на камеру в Android
- 1Ошибка атрибута: у объекта ‘Ball’ нет атрибута ‘x’
- 1AndroidRuntime порка
- 0вызвать функцию через jquery и вывести результаты в div в бритве html
- 0Knockout.js для переключения языков на двуязычном сайте
- 1Автозаполнение имени файла в скрипте Python
- 0SVG элемент из массива
- 0Интервал между <li> в [дубликате]
- 1Magento 2 вызвать пользовательскую библиотеку в select.html
- 0HTML5 — заголовок и схема алгоритма — путаница
- 1Селен: не могу найти элемент
- 1снимок экрана для деятельности
- 1Невозможно запустить очень простой COM-клиент
- 1Использование функции map () в классе
- 0получить число между двумя строками, используя подстроку
- 1Можно ли написать скрипт unittest, который не закрывает браузер при каждом тесте?
- 1Как переопределить свиток в просмотре списка
- 0IE условные комментарии ‘и’?
- 1При подключении в PyQt4 QMessageBox не может вызвать метод слота
- 0Как смоделировать команду curl с Angular
- 0Попытка изменить переменную сеанса CodeIgniter перед загрузкой, работает только на перезагрузку?
- 1Ограничения веб-служб Exchange (EWS)
- 1Создание ярлыка на андроид
- 0Загрузка списка выбора из массива с пробелами
- 1Керас: как реализовать целевую репликацию для LSTM?
- 0mariaDB — не могу связаться с php / страница просто пуста [дубликаты]
- 1javascript ответ загрузки XMLHttpRequest после ответа сервера
- 1Построить высокоточную диаграмму для нескольких серий с использованием данных JSON
- 0Как мне показать div, но сделать его полностью неинтерактивным, в Chrome
- 1Добавить несколько изображений на холст с помощью C #
- 1Изменить логическое значение по умолчанию с помощью OrmLite в БД
- 0Почему обработчики событий не работают после того, как я изменил src изображения?
- 0Как создать уникальную область видимости каждый раз, когда вызывается директива (AngularJS)
- 1Некорректное округление двойных значений валюты
- 0Наверное, очень просто — получить три контейнера рядом друг с другом?
- 1[Vue warn]: Ошибка в функции рендеринга: «TypeError: Невозможно прочитать свойство« совпало »с неопределенным» [duplicate]

Я настраиваю новый сервер и постоянно сталкиваюсь с этой проблемой.
Когда я пытаюсь войти в базу данных MySQL от имени пользователя root, я получаю сообщение об ошибке:
ОШИБКА 1698 (28000): доступ запрещен для пользователя root @ localhost
Не имеет значения, подключаюсь ли я через терминал (SSH), через PHPMyAdmin или клиент MySQL, например Navicat. Все они терпят неудачу.
Я просмотрел таблицу mysql.user и получил следующее:
+------------------+-------------------+
| user | host |
+------------------+-------------------+
| root | % |
| root | 127.0.0.1 |
| amavisd | localhost |
| debian-sys-maint | localhost |
| iredadmin | localhost |
| iredapd | localhost |
| mysql.sys | localhost |
| phpmyadmin | localhost |
| root | localhost |
| roundcube | localhost |
| vmail | localhost |
| vmailadmin | localhost |
| amavisd | test4.folkmann.it |
| iredadmin | test4.folkmann.it |
| iredapd | test4.folkmann.it |
| roundcube | test4.folkmann.it |
| vmail | test4.folkmann.it |
| vmailadmin | test4.folkmann.it |
+------------------+-------------------+
Как видите, root должен иметь доступ.
Сервер довольно прост, так как я уже некоторое время пытался решить эту проблему ..
Он работает под управлением Ubuntu 16.04.1 LTS с Apache, MySQL и PHP, так что он может размещать веб-сайты, и iRedMail 0.9.5-1, чтобы он мог размещать почту.
Вход в базу данных MySQL работает нормально, прежде чем я установлю iRedMail. Я тоже пробовал, просто установил iRedMail, но потом рут, тоже не работает …
Если бы кто-нибудь мог сказать мне, как я могу исправить мою проблему со входом в MySQL или как установить iRedMail поверх существующей установки MySQL. И да, я попробовал Советы по установке и не могу найти эти переменные в файлах конфигурации.
13 ответов
Шаг 1. sudo mysql -u root -p
Шаг 2. USE mysql;
Шаг 3. ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY 'admin';
Здесь admin — ваш новый пароль, вы можете его изменить.
Шаг 4. exit
Спасибо. Вы сделали.
5
Y. Joy Ch. Singha
1 Дек 2018 в 11:04
Я бы предложил удалить соединение Mysql —
ОБНОВЛЕНИЕ-это для Mysql версии 5.5, если ваша версия отличается, пожалуйста, измените первую строку соответственно
sudo apt-get purge mysql-server mysql-client mysql-common mysql-server-core-5.5 mysql-client-core-5.5
sudo rm -rf /etc/mysql /var/lib/mysql
sudo apt-get autoremove
sudo apt-get autoclean
И установите снова Но на этот раз установите пароль root самостоятельно. Это сэкономит много сил.
sudo apt-get update
sudo apt-get install mysql-server
7
Eminem347
15 Окт 2017 в 18:03
Нет необходимости в sudo
База данных инициализируется двумя учетными записями со всеми привилегиями: первая — это «root», которая недоступна, а вторая — с вашим именем пользователя (проверьте с помощью команды whoami).
Чтобы включить доступ к учетной записи root, вам необходимо войти в систему под своим именем пользователя
mysql -u $(whoami)
И вручную изменить пароль для root
use mysql;
set password for 'root'@'localhost' = password('YOUR_ROOT_PASSWORD_HERE');
flush privileges;
quit
Войти как root
mysql -u root -p
7
Raoul HATTERER
10 Янв 2020 в 18:31
В моем случае,
dev@Dev-007:~$ mysql -u root -p
Enter password:
ERROR 1698 (28000): Access denied for user 'root'@'localhost'
Я уверен, что мой пароль верен, иначе код ошибки будет ERROR 1045 (28000): Access denied for user
Поэтому я перехожу в систему с помощью sudo,
dev@Dev-007:~$ sudo mysql -u root -p
На этот раз у меня это сработало. см. документы
А затем измените пароль root,
mysql> alter user 'root'@'%' identified with mysql_native_password by 'me123';
Query OK, 0 rows affected (0.14 sec)
mysql>
Затем перезапустите сервер, используя sudo /etc/init.d/mysql restart
0
Mohideen bin Mohammed
3 Дек 2019 в 13:16
Я нашел свое решение после нескольких часов исследований здесь.
Остановите MySQL
sudo service mysql stop
Создайте каталог служб MySQL.
sudo mkdir /var/run/mysqld
Предоставьте пользователю MySQL разрешение на запись в каталог службы .
sudo chown mysql: /var/run/mysqld
Запустите MySQL вручную, без проверки разрешений и подключения к сети.
sudo mysqld_safe --skip-grant-tables --skip-networking &
Войдите без пароля.
mysql -uroot mysql
обновить пароль
UPDATE mysql.user SET authentication_string=PASSWORD('YOURNEWPASSWORD'), plugin='mysql_native_password' WHERE User='root' AND Host='%';
EXIT;
Отключите MySQL.
sudo mysqladmin -S /var/run/mysqld/mysqld.sock shutdown
Запустите службу MySQL в обычном режиме.
sudo service mysql start
3
Sanjun Dev
3 Сен 2019 в 06:41
Я тоже столкнулся с той же проблемой в первый раз.
Теперь исправлено:
Сначала вы копируете файл /etc/mysql/mysql.conf.d/mysqld.cnf и вставляете его в /etc/mysql/my.cnf.
Сделать это можно командой:
sudo cp /etc/mysql/mysql.conf.d/mysqld.cnf /etc/mysql/my.cnf
Теперь сбросим пароль:
Используйте в своем терминале следующие команды:
sudo service mysql stop
sudo service mysql start
sudo mysql -u root
Теперь вы находитесь в консоли mysql.
Затем напишем несколько запросов для сброса пароля root
USE mysql
update mysql.user set authentication_string=password('newpass') where user='root' and Host ='localhost';
update user set plugin="mysql_native_password";
flush privileges;
quit
Теперь мы можем очистить /etc/mysql/my.cng
Откройте указанный выше файл в своем редакторе и удалите все строки внутри файла.
После этого перезапустим mysql:
sudo mysql service restart
Теперь давайте используем mysql с новым паролем:
sudo mysql -u root -p
Наконец, введите вновь созданный пароль.
3
Samuel Philipp
18 Июл 2019 в 12:04
После нескольких часов борьбы без решения здесь это сработало для меня, затем я нашел видео на YouTube, в котором говорится, что столбец пароля теперь называется authentication_string. Итак, я смог изменить свой пароль следующим образом: Сначала войдите в mysql из терминала
sudo mysql
Затем внутри mysql введите все после mysql>
mysql> use mysql
mysql> update user set authentication_string=PASSWORD("mypass") where user='root';
mysql> flush privileges;
mysql> quit;
В этот момент вы вышли из mysql обратно в свое обычное место терминала. Вам необходимо перезапустить mysql, чтобы это вступило в силу. для этого типа следующее:
sudo service mysql restart
Для лучшего понимания см. эту ссылку на видео
8
Ameer Ul Islam
29 Янв 2020 в 17:09
Вы хотите получить доступ к MySQL от имени пользователя root, но вы не предоставляете правильный пароль root.
Если вам нужно установить новый пароль для root , на сайте MySQL есть отличная документация о том, как это сделать: http://dev.mysql.com/doc/refman/5.7/en/resetting-permissions.html
Я не буду показывать здесь процесс , потому что документация MySql по указанной выше ссылке ясна и кратка .
0
Cristian Gonçalves
2 Сен 2016 в 00:36
Это сработало для меня:
mysql --user=root mysql
CREATE USER 'some_user'@'%' IDENTIFIED BY 'some_pass';
GRANT ALL PRIVILEGES ON *.* TO 'some_user'@'%' WITH GRANT OPTION;
FLUSH PRIVILEGES;
4
Dorad
30 Дек 2018 в 21:19
Это случилось и со мной. Проблема заключается в репозитории mysql, который уже идет с дистрибутивом linux. Итак, когда вы просто делаете: $ sudo apt install mysql-server он устанавливает mysql из своего репо по умолчанию, что создает эту проблему. Итак, чтобы преодолеть это, вам нужно удалить установленный mysql $ sudo apt remove mysql* --purge --auto-remove
Затем загрузите репозиторий mysql с официального сайта mysql MySQL APT Repo Следуйте их документации о том, как добавить репо и установить его. Это не вызывает проблем. Также, как ответил @zetacu, вы можете убедиться, что корень mysql теперь действительно использует плагин mysql_native_password
0
sudip
13 Янв 2019 в 11:03
Отметьте здесь:
НОВАЯ версия MYSQL делает это так.
Если в новом my-sql пароль оставлен пустым во время установки, то он основан на плагине auth_socket.
Правильный способ — войти в my-sql с привилегией sudo.
$ sudo mysql -u root -p
А затем обновить пароль с помощью:
$ ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY 'new-password';
Как только это будет сделано, stop and start сервер MySQL.
$ sudo service mysql stop
$ sudo service mysql start
Для получения полной информации вы можете обратиться к эта ссылка.
Прокомментируйте любые сомнения.
219
Nandesh
25 Окт 2018 в 06:27
У меня была эта проблема на виртуальной машине Debian 8, с которой я взаимодействовал через Putty на моем рабочем столе Windows 10.
Я пробовал различные предложения здесь, но ничего не получилось, и я запускаю MariaDB на хосте Debian. В конце концов, я обнаружил, что не могу запустить сервер db в безопасном режиме, но мне это и не нужно, и следующие команды действительно сработали для меня, то есть позволили вновь созданному пользователю MySql войти на сервер MySql / MariaDB:
sudo service mysql restart
sudo mysql # logs in automatically into MariaDB
use mysql;
update user set plugin='' where user='your_user_name';
flush privileges;
exit;
sudo service mysql restart # restarts the mysql service
Если вышеуказанное не совсем подходит для вас, выполните действия, описанные в сообщении zetacu выше (zetacu), а затем следуйте моим инструкциям. .
Теперь вы должны иметь возможность использовать клиент удаленного терминала и безопасно войти в mysql с помощью команды:
mysql -u your_user_name -p
* введите пароль при появлении запроса
10
kokbira
12 Дек 2018 в 22:11

