Перейти к содержимому

Не удается сбросить пароль root для MySQL (MariaDB)

31

Сегодня я хотел создать базу данных в PMA. Он сказал: «Невозможно войти на сервер MySQL». Я пытался через терминал, та же проблема, и это потому, что мой пароль неверный. И я не могу понять почему.

Я попытался обычным способом сбросить пароль root (пропустить монтирование таблиц грантов и сбросить пароль), но, похоже, он не работает.

Видеть, что:

morgan@rakija:~$ sudo mysqld_safe --skip-grant-tables & [1] 14016 morgan@rakija:~$ 150802 19:07:25 mysqld_safe Can't log to error log and syslog at the same time. Remove all --log-error configuration options for --syslog to take effect. 150802 19:07:25 mysqld_safe Logging to '/var/log/mysql/error.log'. 150802 19:07:25 mysqld_safe A mysqld process already exists  [1]+ Terminé 1 sudo mysqld_safe --skip-grant-tables morgan@rakija:~$ mysql -u root Welcome to the MariaDB monitor. Commands end with ; or \g. Your MariaDB connection id is 2 Server version: 10.0.20-MariaDB-0ubuntu0.15.04.1 (Ubuntu)  Copyright (c) 2000, 2015, Oracle, MariaDB Corporation Ab and others.  Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.  MariaDB [(none)]> use mysql; Database changed MariaDB [mysql]> update user set password=PASSWORD("newPass") where user='root'; Query OK, 4 rows affected (0.00 sec) Rows matched: 4 Changed: 4 Warnings: 0  MariaDB [mysql]> flush privileges; Query OK, 0 rows affected (0.00 sec)  MariaDB [mysql]> exit Bye morgan@rakija:~$ sudo service mysql restart morgan@rakija:~$ mysql -uroot -pnewPass ERROR 1698 (28000): Access denied for user 'root'@'localhost' 
38 600 просмотров
Morgan Touverey Quilling спросил 11 лет назад
M 736

4 ответа

48
Принятый ответ

I have found a solution that is as strange as the problem itself.

Reboot MySQL/MariaDB using --skip-grant-tables (search for tutorials on the web). (not necessary at all, read my edits at the end of the post)

Look at the plugin field into the mysql.user table:

MariaDB [mysql]> SELECT user, plugin FROM user; +------+-------------+ | user | plugin | +------+-------------+ | root | unix_socket | | root | unix_socket | | root | unix_socket | | root | unix_socket | +------+-------------+ 

I had to reset the plugin field of each entry to a blank string.

UPDATE user SET plugin=""; // without WHERE clause 

Also, make sure that a password is defined, because sometimes it seems to be erased (select on user, password fields). If not, update it with:

UPDATE user SET password=PASSWORD("my_password") WHERE user="root"; 

Privileges parameters need to be saved explicitly:

FLUSH PRIVILEGES; 

Then, restart MySQL in normal mode and you should be able to connect to the root account.

This will not necessarily disable the connection via Unix socket. After my MySQL va repaired, in PMA, I can see that the connection is established through an Unix socket.

EDIT, some months later: I'm now used to have this problem come back frequently, I think at each update of MariaDB (or something like that). So I've got a better comprehension of the probem ; there's an UNIX_SOCKET plugin that can let you log in a MariaDB account without having to create a password, because it uses the shell's credentials to trust you, without having to enter any password. In fact, this plugin is an authentication plugin and not a method of communication with the SQL server. So you can safely disable it if you don't use unix socket as a logging-in method. The only thing I can't explain is why the UNIX_SOCKET plugin is regularly set on each account of the database, without any action on my side.

This has the nice side effect that, when it happens, you can login to the SQL server without having to restart MariaDB with --skip-grant-tables: just log-in to the system's root account, then just connect with mysql -u root without password, then reset the plugin field in the way it is explained above.

EDIT 2: Confirmed, it happens on each MariaDB upgrade on Ubuntu.

Это нарушает работу cron по обслуживанию в Ubuntu 16.04 (по крайней мере), потому что этот сценарий ожидает входа в систему без пароля с помощью плагина сокета. См. Https://superuser.com/questions/957708/mysql-mariadb-error-1698-28000-access-denied-for-user-rootlocalhost/1103735 для получения подробной информации.

colan · 10 лет назад · 1

Ладно, интересно, но этого больше не происходит (моя установка старых паролей теперь не случайна). Может быть, плагин для сокета Unix установлен только для пользователя root? Не могу проверить это прямо сейчас. Но мне не нравится идея, что ОС решает, какую настройку аутентификации использовать.

Morgan Touverey Quilling · 10 лет назад · 0

Эта проблема отстой, это произошло в Debian 9, когда я установил MariaDB, пароль root не спрашивался, и я даже не смог его сбросить. Я надеюсь, что это не повторится после обновления. Должны ли мы заменить MariaDB на MySQL, чтобы избежать таких проблем?

baptx · 8 лет назад · 0

Не уверен, что это все еще происходит, возможно, это было исправлено сейчас (я могу редактировать пост, если кто-нибудь знает). Может быть, это происходит только при установке, которая будет хорошей настройкой по умолчанию.

Morgan Touverey Quilling · 8 лет назад · 0

Я только что заметил, что если мы не используем плагин сокета unix для пользователя root, он не сможет установить пакет phpmyadmin на последнем Debian: ERROR 1045 (28000): доступ запрещен для пользователя 'root' @ 'localhost' (используя пароль: НЕТ). Поэтому лучшим решением будет продолжать использовать аутентификацию сокетов Unix по умолчанию с командой sudo mysql -u root`, которая, на мой взгляд, также более безопасна и эффективна.

baptx · 8 лет назад · 1

Да, при каждом обновлении с mysql до mariadb у нас возникают проблемы с учетной записью пользователя root ... ахх ..

Melroy · 8 лет назад · 0
Morgan Touverey Quilling ответил 11 лет назад
M 736
4

From this answer, http://ubuntuforums.org/showthread.php?t=2275033&p=13272227#post13272227.

Mysql tries to authenticate root using plugin, not password. You need to disable plugin usage for root.

shell$ sudo mysql -u root [mysql] use mysql; [mysql] update user set plugin='' where User='root'; [mysql] flush privileges; [mysql] \q 

Это именно то, что я написал в качестве ответа.

Morgan Touverey Quilling · 10 лет назад · 2

Это немного более краткий свод с вашим обновлением.

ponies · 10 лет назад · 0
ponies ответил 10 лет назад
P 161
0

Connect as previously described:

mysqld_safe --skip-grant-tables 

Log file will be showed:

160518 23:21:01 mysqld_safe Logging to '/usr/local/mysql/data/ab123456.domain.com.err'. 160518 23:21:01 mysqld_safe Starting mysqld daemon with databases from /usr/local/mysql/data 

Search log listed (in this case: /usr/local/mysql/data/ab123456.domain.com.err) for right socket:

cat /usr/local/mysql/data/ab123456.domain.com.err | grep "socket: " Version: '5.5.49-MariaDB' socket: '/tmp/mysql.sock' port: 3306 MariaDB Server 

and use it in mysql connection:

mysql --socket /tmp/mysql.sock -u root root@ab123456:~# /usr/local/mysql/bin/mysql --socket /tmp/mysql.sock -u root Welcome to the MariaDB monitor. Commands end with ; or \g. Your MariaDB connection id is 1 Server version: 5.5.49-MariaDB MariaDB Server 
wiesia.stachanczyk ответил 10 лет назад
W 1
0

По умолчанию marriadb использует плагин аутентификации "unix_socket" для установки паролей, это должно быть "mysql_native_password", поэтому

переключить базу данных ..

use mydatabase; 

Первый плагин ведьмы установлен ..

SELECT user, plugin FROM user; 

установите его в "mysql_native_password"

UPDATE user SET plugin="mysql_native_password"; 

установить новый пароль ...

update user set authentication_string=password('My@Password'), plugin='mysql_native_password' where user='root'; 
André Verwijs ответил 9 лет назад
A 141