- Содержание
- Тема: проблема с mysql server 5.5 не могу зайти как рут. (Прочитано 2499 раз)
- olegRomanuk
- Protopopulus
- olegRomanuk
- victor00000
- olegRomanuk
- Protopopulus
- olegRomanuk
- victor00000
- Protopopulus
- olegRomanuk
- Solution 1: Sudo then Change Password
- Solution 2: Edit My.cnf File
- Conclusion
- Администрирование
- Установка root пароля
- Восстановление забытого пароля для root’a
- Резервное копирование
- Отключение и включение автозагрузки сервиса
- Сброс пароля с помощью skip-grant-tables
- Solve Access Denied for User Root Error
- Steps to change plugin and password
- Настройка
- Доступ к серверу из сети
- Кодировки
- MySQL Workbench
- Установка
- Test Root User MySQL Access
- Cause of the issue
- Сброс пароля с помощью init-file
- Об авторе
- Выводы
Содержание
MySQL — свободная СУБД для малых и средних приложений. Входит в состав LAMP и XAMPP.

- Access to a command line or terminal window
- MySQL or MariaDB installed
- User with sudo or root privileges
mysql -u root -p
You can enable access for root using one MySQL command.
Для доступа к базе данных MySQL или MariaDB нужно ввести имя пользователя и пароль. Во время установки автоматически создаётся учётная запись пользователя root. Это аналог суперпользователя в Linux для MySQL. Он может выполнять все действия со всеми базами данных, а также создавать и удалять других пользователей.
Обычно, пароль для него не устанавливается, и вы можете задать его вручную уже после завершения установки. Но если вы забыли пароль или он был установлен автоматически, но вы его не знаете, то вам может понадобится его сбросить. Это можно сделать несколькими способами. В этой статье мы разберём, как выполняется сброс пароля root MySQL.
В статье я буду использовать Ubuntu и MariaDB, но эта инструкция подойдёт и для других дистрибутивов. В командах с systemctl для Mariadb следует использовать mariadb, а для MySQL — mysql или mysqld.
In short, on MariaDB
UPDATE mysql.user SET plugin = 'mysql_native_password', Password = PASSWORD('NEWPASSWORD') WHERE User = 'root';where you replace NEWPASSWORD with the password you want, and everything else verbatim.
mysql -uroot -pselect User,host,plugin from mysql.user;
+----------------+-----------+-----------------------+
| User | host | plugin |
+----------------+-----------+-----------------------+
| root | localhost | auth_socket |
+----------------+-----------+-----------------------+On MariaDB (<10.2, see comments below) which is on the Ubuntu version 16 as of 2017 this should suffice. NEWPASSWORD is your password. mysql_native_password you type verbatim.
UPDATE mysql.user SET plugin = 'mysql_native_password', Password = PASSWORD('NEWPASSWORD') WHERE User = 'root';(It’s possible that setting the plugin to empty would work. YMMV. I didn’t try this. So this is an alternative.)
UPDATE mysql.user SET plugin = '', Password = PASSWORD('NEWPASSWORD') WHERE User = 'root';ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY 'NEWPASSWORD';FLUSH PRIVILEGES;1) Install MariaDB
sudo apt-get -y install mariadb-server mariadb-client
sudo mysql_secure_installation (answer to some interactive questions): Enter current password for root (enter for none): <enter> Set root password: n Remove anonymous users: n Disallow root login remotely: n Remove test database and access to it: n Reload privilege tables now: YIf you want to uninstall mariaDB:
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 autocleansudo apt-get -y install phpmyadmin (and answer some interactive questions) Configuring phpmyadmin: Web server to reconfigure automatically: apache2 Configure database for phpmyadmin with dbconfig-common: Yes MySQL application password for phpmyadmin: <blank>sudo ln -s /etc/phpmyadmin/apache.conf /etc/apache2/conf-available/phpmyadmin.conf
sudo a2enconf phpmyadmin.conf
sudo service apache2 restartsudo dpkg-reconfigure phpmyadmin
<Ok>
Reinstall database for phpmyadmin: <Yes>
Connection method for MySQL database server for phpmyadmin: TCP/IP
Host name of the MySQL database server for phpmyadmin: localhost
Port number for the MySQL service: 3306
MySQL database name for phpmyadmin: phpmyadmin
<Ok>
MySQL username for phpmyadmin: root
MySQL application password for phpmyadmin: pass # OR ANY PASSWORD YOU WANT
Password confirmation: pass
Name of the database's administrative user: root
Web server to reconfigure automatically: apache2
An error occurred while installing the database: ignoreusername: root
password: passyou’ll be able to create databases.
Тема: проблема с mysql server 5.5 не могу зайти как рут. (Прочитано 2499 раз)
0 Пользователей и 1 Гость просматривают эту тему.
sudo apt-get install mysql-serverwhich has installed
mysql Ver 14.14 Distrib 5.7.16, for Linux (x86_64) using EditLine wrappeand this went through a few «gui» screens prompting me for passwords. I just hit enter for each, which I thought was like saying «No password».
But now, I thought i’d be able to get into it with mysql -u root, but it says
ERROR 1698 (28000): Access denied for user 'root'@'localhost'I tried a reboot just in case. Is the problem that I’m not using the right password, or is it something more fundamental? If it’s the password, how to I find out what it is/reset it? Thanks, Max
sudo service mysql stop
sudo mysqld_safe --skip-grant-tables &
mysql -u rootthen in mysql, i try to change the password but it doesn’t recognise the field name: I do a desc to see what is in there:
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
mysql> update user set password=PASSWORD("password") where User='root';
ERROR 1054 (42S22): Unknown column 'password' in 'field list'
mysql> desc user;
+------------------------+-----------------------------------+------+-----+-----------------------+-------+
| Field | Type | Null | Key | Default | Extra |
+------------------------+-----------------------------------+------+-----+-----------------------+-------+
| Host | char(60) | NO | PRI | | |
| User | char(32) | NO | PRI | | |
| Select_priv | enum('N','Y') | NO | | N | |
| Insert_priv | enum('N','Y') | NO | | N | |
| Update_priv | enum('N','Y') | NO | | N | |
| Delete_priv | enum('N','Y') | NO | | N | |
| Create_priv | enum('N','Y') | NO | | N | |
| Drop_priv | enum('N','Y') | NO | | N | |
| Reload_priv | enum('N','Y') | NO | | N | |
| Shutdown_priv | enum('N','Y') | NO | | N | |
| Process_priv | enum('N','Y') | NO | | N | |
| File_priv | enum('N','Y') | NO | | N | |
| Grant_priv | enum('N','Y') | NO | | N | |
| References_priv | enum('N','Y') | NO | | N | |
| Index_priv | enum('N','Y') | NO | | N | |
| Alter_priv | enum('N','Y') | NO | | N | |
| Show_db_priv | enum('N','Y') | NO | | N | |
| Super_priv | enum('N','Y') | NO | | N | |
| Create_tmp_table_priv | enum('N','Y') | NO | | N | |
| Lock_tables_priv | enum('N','Y') | NO | | N | |
| Execute_priv | enum('N','Y') | NO | | N | |
| Repl_slave_priv | enum('N','Y') | NO | | N | |
| Repl_client_priv | enum('N','Y') | NO | | N | |
| Create_view_priv | enum('N','Y') | NO | | N | |
| Show_view_priv | enum('N','Y') | NO | | N | |
| Create_routine_priv | enum('N','Y') | NO | | N | |
| Alter_routine_priv | enum('N','Y') | NO | | N | |
| Create_user_priv | enum('N','Y') | NO | | N | |
| Event_priv | enum('N','Y') | NO | | N | |
| Trigger_priv | enum('N','Y') | NO | | N | |
| Create_tablespace_priv | enum('N','Y') | NO | | N | |
| ssl_type | enum('','ANY','X509','SPECIFIED') | NO | | | |
| ssl_cipher | blob | NO | | NULL | |
| x509_issuer | blob | NO | | NULL | |
| x509_subject | blob | NO | | NULL | |
| max_questions | int(11) unsigned | NO | | 0 | |
| max_updates | int(11) unsigned | NO | | 0 | |
| max_connections | int(11) unsigned | NO | | 0 | |
| max_user_connections | int(11) unsigned | NO | | 0 | |
| plugin | char(64) | NO | | mysql_native_password | |
| authentication_string | text | YES | | NULL | |
| password_expired | enum('N','Y') | NO | | N | |
| password_last_changed | timestamp | YES | | NULL | |
| password_lifetime | smallint(5) unsigned | YES | | NULL | |
| account_locked | enum('N','Y') | NO | | N | |
+------------------------+-----------------------------------+------+-----+-----------------------+-------+
45 rows in set (0.00 sec)Not sure what to do next — also, what is the syntax for setting no password? Is it just set password=''?
My mysql version is:
Server version: 5.7.16-0ubuntu0.16.04.1 (Ubuntu)
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_installationSecuring 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.
This “access denied” error is one of the most common errors you’ll get when working with MySQL.
Learn how to fix it, and see a range of solutions if the suggested fix does not work, in this article.
When you try to connect to a MySQL database on your own computer (called “localhost”), you may get this error:
Access denied for user 'root'@'localhost' (using password: YES)
You might get an error code in front of it:
ERROR 1045 (28000): Access denied for user 'root'@'localhost' (using password: YES)
You might also get the error with “using password no”:
Access denied for user 'root'@'localhost' (using password: NO)
You’ll see this if you log into MySQL using the command line:
mysql -u root -p
What does this mean? How can you fix it?
There are a few solutions to this, which I’ve detailed below. Try one, and if it doesn’t work, try another one.
Also a tip for logging in: don’t enter your password in the command line itself, because this will be stored in your command history. Use the -p option, as mentioned above, and then you’ll be prompted to enter the password.
Solution 1: Sudo then Change Password
If you get the “access denied” error, one way to solve it is by using sudo to log in to mysql and change the root password.
Step 1: Open the command line on your system.
Step 2: Open mysql using the sudo command:
sudo mysql
Step 3: Enter the password for this account.
Step 4: Change the auth_plugin to mysql_native_password, and the password for the root account, in a single command:
ALTER USER 'root'@'localhost'
IDENTIFIED WITH mysql_native_password BY 'your_new_password';Substitute the word your_new_password with a new secure password that you want to use for the root account.
The mysql_native_password method is a traditional method of authentication and will allow you to login.
Step 5: Flush the privileges, which tells the server to refresh the grant tables and apply your changes, with this command:
FLUSH PRIVILEGES;SELECT user, plugin
FROM mysql.userStep 7: Exit the console by pressing CTRL + D or typing exit.
exit;
Step 8: Log in to mysql using the root account and the new password you set, which should work:
mysql -u root -p
You should now be logged in to the root account in mysql.
Solution 2: Edit My.cnf File
If the above solution did not work, you may need to edit the mysql.cnf file to allow for changes to the root account.
Step 1: Open the my.cnf file. This may be stored in:
/etc/my.cnf /etc/mysql/my.cnf
If you’re not sure where it is, search your MySQL installation folder (e.g. on Windows or Mac) for the file.
If you don’t have a my.cnf file (MacOS does not include one by default). You can create one in the /etc folder if you like.
[mysqld] skip-grant-tables
Step 3: Restart the MySQL server.
Step 4: Login to the root account:
mysql -u root -p
Step 5: Flush the privileges, which tells the server to refresh the grant tables and apply your changes, with this command:
FLUSH PRIVILEGES;Step 6: Set a new password for the account:
ALTER USER 'root'@'localhost' IDENTIFIED BY 'your_new_password';Substitute the word your_new_password with a new secure password that you want to use for the root account.
Step 7: Open the my.cnf file you opened in step 1, and remove the line about skip-grant-tables, and save the file.
Step 8: Restart the MySQL server again.
Step 9: Log in to the root account again:
mysql -u root -p
You should now be able to log in successfully with your new password and not get an error.
Conclusion
If you have any questions, feel free to use the comments section below.
Администрирование
Установка root пароля
sudo mysql_secure_installation
Восстановление забытого пароля для root’a
Схожая проблема возникает если не задать пароль при установке MySQL, в этом случае mysql использует плагин unix-socket.
service mysql stop
mysqld =root
Подключитесь к MySQL-серверу командой:
mysql root
service mysql restart
Теперь можете проверить вход под root с новым паролем:
mysql root
Резервное копирование
Для создания резервных копий существует специальная утилита mysqldump. Основные ее параметры приведены в таблице:
Отключение и включение автозагрузки сервиса
Начиная с версии Ubuntu 15.04 отключение и включение сервисов возможно одной командой, без редактирования конфигов. В примерах команд ниже слово «SERVICE» следует заменить на «mysql».
Узнать стоит ли сервис в автозагрузке:
$ systemctl is-enabled SERVICE
Убрать сервис из автозагрузки в Ubuntu-16.04:
$ sudo systemctl disable SERVICE
Добавить сервис в автозагрузку в Ubuntu-16.04:
$ sudo systemctl enable SERVICE
Сброс пароля с помощью skip-grant-tables
Кроме того, есть и другой способ сбросить пароль MySQL. Мы можем запустить сервис с параметром —skip-grant-tables. В этом режиме программа пропускает загрузку данных о пользователях и тогда вы можете авторизоваться без ввода пароля. Аналогично, сначала нужно остановить сервис:
sudo systemctl stop mariadb
Затем запустите mysql вручную с помощью такой команды:

Войдите в консоль управления mysql:
mysql -u root

Так как мы загрузились без таблиц привелегий пользователей, то эти таблицы необходимо подгрузить сейчас:

Теперь можно сменить пароль для пользователя root:

Затем закройте консоль клиента mysql:
Завершите запущенный вручную сервис, таким же образом как в предыдущем пункте:
sudo kill -TERM 5356
И запустите mysql в нормальном режиме:
sudo systemctl start mariadb
Дальше вы можете авторизоваться от имени суперпользователя по этому паролю:
sudo mysql -u root -p
Solve Access Denied for User Root Error
sudo mysqlEnter your password at the prompt. A MySQL shell loads.

ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY 'insert_password';Steps to change plugin and password
open terminal and run
sudo mysql -u root. You should see a greeting message andmysql>prompt. This is the MySQL shell, which is different from your command-line shell, so only SQL statements are accepted here.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 mysql> flush privileges; Query OK, 0 rows affected (0.00 sec) mysql> UPDATE user SET plugin='mysql_native_password',authentication_string=PASSWORD('newpassword') WHERE user = 'root'; Query OK, 1 row affected, 1 warning (0.00 sec) Rows matched: 1 Changed: 1 Warnings: 1Exit and attempt to sign in:
mysql> exit Bye $ sudo systemctl restart mysql $ sudo mysql -u root -p Enter password: Welcome to the MySQL monitor. Commands end with ; or \g. Your MySQL connection id is 5 Server version: 5.7.21-1 (Debian) Copyright (c) 2000, 2018, 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>
Настройка
Конфигурация сервера MySQL содержится в файле /etc/mysql/my.cnf.
Доступ к серверу из сети
По умолчанию сервер MySQL принимает соединения только с локальной машины. Для того, чтобы разрешить подключаться к нему с других машин замените строку
#разрешить подключатся с любого хоста #разрешить подключатся только с указанного IP
Кодировки
В данном разделе используется распространённое решение проблемы с кодировкой. Стоит помнить, что данное решение не является правильным, хоть и помогает временно решить проблему. Для правильного использования кодировки создавайте или храните таблицы в любой удобной для хранения в СУБД кодировке, а вот клиент должен подключаться к СУБД с указанием той кодировки, с которй выводится текст или производится обработка данных.
По-умолчанию в Ubuntu MySQL устанавливается с кодировкой latin1. В этом можно убедиться посмотрев вывод запроса:
VARIABLES
character_set_client latin1 character_set_connection latin1 character_set_database latin1 character_set_filesystem binary character_set_results latin1 character_set_server latin1 character_set_system utf8 character_sets_dir /usr/share/mysql/charsets/
В связи с этим, даже используя при работе с сервером команду
names utf8
и используя при создании таблиц
... CHARACTER utf8 utf8_general_ci
невозможно добиться полной поддержки кодировки utf8:
character_set_client utf8 character_set_connection utf8 ... character_set_server latin1 ... character_sets_dir /usr/share/mysql/charsets/
Кодировка по-умолчанию все равно останется latin1, что неудобно и может привести к ошибкам.
Чтобы сервер сразу загружался с нужной кодировкой, необходимо отредактировать файл /etc/mysql/my.cnf:
etcmysqlmy.cnf
skip-character-set-client-handshake 'SET NAMES utf8'Перезагрузите сервер MySQL:
service mysql restart
После этого список переменных будет выглядеть так:
character_set_client utf8 character_set_connection utf8 character_set_database utf8 character_set_filesystem binary character_set_results utf8 character_set_server utf8 character_set_system utf8 character_sets_dir /usr/share/mysql/charsets/
Если на момент изменения настроек кодировки в базе уже присутствовали записи содержащие кириллицу, то они будут иметь неверную кодировку. Перед изменением кодировки убедитесь что в базе нет таблиц и данных, либо сделайте дамп всех данных из базы до внесения изменений настроек и восстановите после внесения изменений и перезагрузки MySQL.
MySQL Workbench
MySQL Workbench – инструмент для визуального проектирования баз данных. MySQL Workbench существует в двух вариантах:
Community Edition – бесплатная версия, распространяемая под лицензией GPL3
Standard Edition – платная версия, включающая в себя некоторые дополнительные возможности.
Пакет вложенный на официальном сайте не подходит для Ubuntu 12.04 и выше. Это связано с тем, что пакет libzip1, прописанный в зависимостях был исключен из репозиториев. Как временное решение используйте PPA ppa:olivier-berten/misc .
Установка
MySQL есть в репозиториях Ubuntu. Он разбит на несколько пакетов.
Для того чтобы установить MySQL сервер выполните команду:
mysql-server
При установке конфигурационный скрипт запросит пароль для администратора (root) базы данных.
Для того чтобы установить консольный клиент MySQL выполните команду:
mysql-client
Для того чтобы установить модуль для работы с MySQL в PHP выполните команду:
php5-mysql
Test Root User MySQL Access
After you run the commands listed above, exit the MySQL shell by pressing CTRL + D on your keyboard or type exit; and hit enter. There is no need to restart the mysqld service to log in.
Now try again to access MySQL with root. In the terminal, type in:
mysql -u root -pThere are different ways to approach this issue, but we selected the easiest and fastest method. Make sure to enter the commands as listed in the article to avoid errors in SQL syntax.
Cause of the issue
mysql> select user,authentication_string,plugin from user where user='root';
+------+-----------------------+-------------+
| user | authentication_string | plugin |
+------+-----------------------+-------------+
| root | | auth_socket |
+------+-----------------------+-------------+
1 row in set (0.00 sec)From the documentation:
Сброс пароля с помощью init-file
При запуске сервиса MySQL можно указать файл, из которого будут выполнены команды sql сразу после запуска. Адрес этого файла указывается опцией —init-file. Но сначала давайте создадим файл, который будет изменять файл нашего пользователя:

Затем остановите сервис, если он запущен:
sudo systemctl stop mysql
sudo systemctl stop mariadb

Теперь осталось выполнить наш файл:

Подождите минуту, чтобы всё успело сработать как нужно, а затем остановите этот процесс. В консоли команда сообщит started as proccess и PID процесса, этот PID нам и нужен, чтобы его остановить. Например:
sudo kill -TERM 5356

sudo systemctl start mariadb
mysql -u root -p
Об авторе
![]()
Основатель и администратор сайта losst.ru, увлекаюсь открытым программным обеспечением и операционной системой Linux. В качестве основной ОС сейчас использую Ubuntu. Кроме Linux, интересуюсь всем, что связано с информационными технологиями и современной наукой.
Выводы
Обнаружили ошибку в тексте? Сообщите мне об этом. Выделите текст с ошибкой и нажмите Ctrl+Enter.







