Как узнать пароль от mysql
Перейти к содержимому

Как узнать пароль от mysql

  • автор:

Как найти и сменить пароль пользователя MySQL?

Как узнать пароль MySQL или не ищем приключений на свою голову

Дата публикации:
2016-05-03

От автора:
вы куда полезли через ограду, гражданин! На заборе написали пароль, чтоб не забыть. Так может вы с этой стороны написали? Да нет – это не мой написан. Ну, удачных поисков, а всем остальным я расскажу, как узнать пароль MySQL, не перелезая через чужие заборы.

Нет ничего проще!

Если у вас есть элементарные знания и навыки обращения с СУБД MySQL, и (главное) учетная запись администратора, то узнать пароли всех пользователей можно в два счета. Для этого можно использовать как программные оболочки, так и команды SQL.

Что представляет собой сервер СУБД? Это обычная база данных, содержащая в себе всю нужную для работы MySQL информацию. Здесь хранятся все настройки сервера, баз, сведения о плагинах, дате и времени, пользовательские учетные записи, их привилегиях и паролях. В контексте данной статьи нас интересует значения последних.

Чтобы узнать пароль MySQL, нужно зайти на сервер под своей учеткой администратора. Затем открыть системную базу данных с именем «mysql» и сделать выборку значений из таблицы user. Для наглядности все интересующие сведения (значения паролей) мы получим с помощью php MyAdmin.

Откроем системную БД, и посмотрим на содержимое нужной нам таблицы «сблизи»: в одном из ее столбцов прописаны все пароли. Как видите, ничего сложного и для этого нам понадобилось всего несколько минут. Но что это такое? Кто «стибрил» из таблицы понятные значения паролей и заменил их какой-то «абракадаброй»!

Бесплатный курс по PHP программированию

Освойте курс и узнайте, как создать динамичный сайт на PHP и MySQL с полного нуля, используя модель MVC

В курсе 39 уроков | 15 часов видео | исходники для каждого урока

Получить курс сейчас!

Спокойствие, и только спокойствие! Никто ничего «не стибрил», просто в таблице указываются уже хешированные пароли. А что у вас глаза такие удивленные? Сейчас все разложим «по полочкам».

Как происходит шифрование в MySQL

Дело в том, что данная СУБД использует собственный алгоритм шифрования паролей. Точнее, не шифрования, а хеширования. Из-за этого пока никто не придумал способа, как расшифровать пароли в MySQL.

Существуют различные алгоритмы хеширования, но если при этом будет использоваться криптографическая толь, то шансов получить значение пароля сводится почти к 0. Криптографическая соль – это дополнительная строка, которая присоединяется к первоначальному значению. В результате на выходе (после хеширования) получается почти «невзламываемый» пароль.

Для установки пароля СУБД использует функцию PASSWORD(). Она не возвращает значения, которое было послано ей на обработку. Поэтому использовать данную функцию для получения «читаемого» пароля не получится. Единственное, что можно сделать – это получить хешированную строку по первоначальному значению. Синтаксис запроса:

Это же значение можно найти в системной таблице user (служебная база данных mysql), куда заносятся все учетные записи пользователей СУБД и хешированные значения паролей.

Путем перебора (если знать хотя бы примерную структуру значения) можно попытаться вспомнить забытый пароль. Но восстановить таким образом полностью неизвестное значение практически невозможно. Помните, что все описанные выше операции производятся под учетной записью администратора (root).

Использование обратимого шифрования

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

Например, если открыть таблицу БД WordPress, где движок сохраняет все данные о пользователях, то в столбце user_pass вы увидите такую же «абракадабру», как и в системной базе MySQL. Это говорит о том, что данная CMS также использует один из алгоритмов необратимого шифрования паролей (md5).

Но можно реализовать схему аутентификации на основе обратимых методов шифрования. Этим и займемся. Не будем сегодня огорчать себя «черным» цветом, и все запросы SQL выполним не через командную строку, а в phpMyAdmin. Для экспериментов я воспользуюсь тестовой БД «db1», в которой хранится одна таблица со «зверюшками» (animal). Добавим новую таблицу с именами хозяев зверей и паролем для входа в их «клетки»

Бесплатный курс по PHP программированию

Освойте курс и узнайте, как создать динамичный сайт на PHP и MySQL с полного нуля, используя модель MVC

В курсе 39 уроков | 15 часов видео | исходники для каждого урока

Получить курс сейчас!

Теперь перед тем, как узнать пароль MySQL, давайте заполним созданную таблицу данными. Для этого мы снова используем запросы SQL, как поступают настоящие разработчики. Код запроса:

Меняя значения в скобках после оператора VALUES, добавьте в таблицу еще несколько строк. Теперь сделаем из нее выборку данных:

Вообще-то непорядок получается! Значение паролей всех пользователей видны «как на ладони». Сейчас мы их слегка «хешанем» с помощью встроенной функции AES_ENCRYPT. Она принимает 2 параметра: столбец для хеширования и значение «соли»:

Теперь давайте еще раз сделаем выборку из таблицы и посмотрим на ее результаты:

Как видите, одни «блобы» получились вместо паролей. Это говорит о том, что значения надежно хешированы, и без «соли» взломать их практически невозможно. Но мы с вами знаем, в чем «соль». Сейчас я вам покажу, как узнать пароли к базе данных MySQL, точнее вернуть их в более «читаемом» виде. Для этого используется другая функция — AES_DECRYPT(). Код запроса с ее «участием»:

Результаты этой выборки:

Как видите, чтобы узнать пароль MySQL, нужно правильно понимать, в чем «соль» проблемы. А если лазить по чужим заборам, то можно запросто получить заряд соли (из ружья) в то место, на которое не стоит лишний раз искать приключений. Лучше это время потратить на изучение MySQL.

Бесплатный курс по PHP программированию

Освойте курс и узнайте, как создать динамичный сайт на PHP и MySQL с полного нуля, используя модель MVC

MySQL Default Password – How To Find And Reset It

When installing MySQL, you may noticed that it does not ask for a password. This become troublesome when you want to connect your application to MySQL database. In this article, I will show you on how to find MySQL default password.

MySQL Default Password

Well, straight forward, by default the username is root and there is no password setup. You may need to reset the root password.

Also, in case you have accidently put a password during installation process and can’t recall the password, you need to reset the password.

There is no way to view the password as it’s already written as hashed.

How To Reset MySQL Default Password

Windows OS

1. Ensure that your logged on account has administrator rights.

2. On the windows search box, search for services.msc and click to open.

3. Scroll down to all services with its status. Find MySQL services, right-click on it and click stop services.

4. Create a text file which contains the SQL statement in a single line as below:

ALTER USER ‘root’@’localhost’ IDENTIFIED BY ‘MyNewPass’;

Change MyNewPass to your new desired password.

5. Save it to a text file. For example, save it as C:\new-password.txt.

6. On the windows search box, search for cmd and click Run as administrator.

7. Start the MySQL with init_file system variable set to text file name created as below:

C:\> cd “C:\Program Files\MySQL\MySQL Server 5.7\bin” C:\> mysqld –init-file=C:\\mysql-init.txt

You may replace your MySQL installation location after cd command.

Linux

1. Open terminal.

2. Stop MySQL server.

sudo service mysql stop

sudo /usr/local/mysql/support-files/mysql.server stop

3. Start MySQL in safe mode.

sudo mysqld_safe –skip-grant-tables

4. Open another terminal and login as root by run below command.

3. Once MySQL is logged in via terminal, run below queries.

UPDATE mysql.user SET authentication_string=PASSWORD(‘password’) WHERE User=’root’; FLUSH PRIVILEGES;

which be looks like:

mysql>UPDATE mysql.user SET authentication_string=PASSWORD(‘password’) WHERE User=’root’; FLUSH PRIVILEGES;

(Note: In MySQL 5.7, the password field in mysql.user table field was removed, now the field name is ‘authentication_string’.)

If you are using MySQL 5.7 and above you need to run command as below:

mysql> use mysql; mysql>update user set authentication_string=password(‘password’) where user=’root’; FLUSH PRIVILEGES;

4. Now, you can exit MySQL safe mode.

If you received error ‘access denied’ you can run below command with the new password:

mysqladmin -u root -p shutdown

5. Start MySQL service again by run below command.

sudo service mysql start

What If Still Failed To Reset MySQL Default Password?

If by using ALTER USER still not able to reset password, you may try to modify the user table directly by repeating the steps above and run below query:

Как узнать пароль от mysql

# systemctl stop mysqld
# /usr/sbin/mysqld —skip-grant-tables -u mysql &

$ mysql
mysql> flush privileges;
Query OK, 0 rows affected (0.00 sec)

mysql> SET PASSWORD FOR ‘root’@’localhost’ = PASSWORD(‘MyNewPass’);
Query OK, 0 rows affected, 1 warning (0.01 sec)

# kill %1
# systemctl start mysqld

$ mysql -u root -p
Enter password:
Welcome to the MySQL monitor. Commands end with ; or \g.
.
mysql>

How to find out the MySQL root password

I cannot figure out my MySQL root password; how can I find this out? Is there any file where this password is stored?

I am following this link but I do not have directadmin directory in local.

Ben's user avatar

21 Answers 21

thanks to @thusharaK I could reset the root password without knowing the old password.

On ubuntu I did the following:

Then run mysql in a new terminal:

And run the following queries to change the password:

In MySQL 5.7, the password field in mysql.user table field was removed, now the field name is ‘authentication_string’.

Quit the mysql safe mode and start mysql service by:

You can’t view the hashed password; the only thing you can do is reset it!

Start it in safe mode:

(above line is the whole command)

This will be an ongoing command until the process is finished so open another shell/terminal window, log in without a password:

MySQL 5.7 and over:

Exit the MySQL CLI:

Restart MySQL in normal mode, first stopping the safe mode instance:

Your new password is ‘password’.

Reg Edit's user avatar

tk_'s user avatar

MySQL 5.7 and above saves root in MySQL log file.

Please try this:

One thing that tripped me up on a new install of MySQL and wondering why I couldn’t get the default password to work and why even the reset methods where not working. Well turns out that on Ubuntu 18 the most recent version of MySQL server does not use password auth at all for the root user by default. So this means it doesn’t matter what you set it to, it won’t let you use it. It’s expecting you to login from a privileged socket.

This will not work, even if you are using the correct password.

Instead, you need to use:

that will work with out any password. then once you in you need type in

Then log out and now it will accept your password.

Jakov's user avatar

Kit Ramos's user avatar

Follow these steps to reset password in Windows system

Stop Mysql service from task manager

Create a text file and paste the below statement

MySQL 5.7.5 and earlier:

SET PASSWORD FOR ‘root’@’localhost’ = PASSWORD(‘yournewpassword’);

MySQL 5.7.6 and later:

ALTER USER ‘root’@’localhost’ IDENTIFIED BY ‘yournewpassword’;

Save as mysql-init.txt and place it in ‘C’ drive .

Open command prompt and paste the following

C:\> mysqld —init-file=C:\\mysql-init.txt

Lokesh kumar Chippada's user avatar

You cannot find it. It is stored in a database, which you need the root password to access, and even if you did get access somehow, it is hashed with a one-way hash. You can reset it: How to Reset the Root Password

Kuro Neko's user avatar

This worked for me:

On terminal type the following

$ sudo mysql -u root -p

Enter password://just press enter

Unless the package manager requests you to type the root password during installation, the default root password is the empty string. To connect to freshly installed server, type:

To change the password, get back the unix shell and type:

The new password is ‘root’. Now connect to the server:

Oops, the password has changed. Use the new one, root :

Bingo! New do something interesting

As addition to the other answers, in a cpanel installation, the mysql root password is stored in a file named /root/.my.cnf . (and the cpanel service resets it back on change, so the other answers here won’t help)

you can view mysql root password , well i have tried it on mysql 5.5 so do not know about other new version well work or not

The default password which worked for me after immediate installation of mysql server is : mysql

LinusGeffarth's user avatar

The procedure changes depending the version of MySql. Follow the procedure exactly as described for your version:

HINTS — Read before the instructions page for your version of MySql*

In step 5: Instead of run CMD, create a shortcut on your desktop calling CDM.exe. Then right-click on the shortcut and select «Execute as Administrator».

In step 6: Skip the first proposed version of the command and execute the second one, the one with the —defaults-file parameter

Once you execute the command, if everything is ok, the CMD window remains open and the command of step 6 continues executing. Simply close the window (click ‘x’), and then force close MySQl from the Task Manager.

Delete the file with the SQL commands, and start again MySQL. The password must be changed now.

. just change the version in the link (5.5, 5.6, 5.7)

In your «hostname».err file inside the data folder MySQL works on, try to look for a string that starts with:

«A temporary password is generated for roor@localhost «

then slash command followed by the string you wish to look for

Then press n, to go to the Next result.

nDCasT's user avatar

I solved this a different way, this may be easier for some.

I did it this way because I tried starting in safe mode but cannot connect with the error: ERROR 2002 (HY000): Can’t connect to local MySQL server through socket ‘/var/run/mysqld/mysqld.sock’ (2)

What I did was to connect normally as root:

Then I created a new super user:

Then log in as myuser

Trying to change the password gave me no errors but did nothing for me so I dropped and re-created the root user

The root user is now working with the new password

Using Debian / Ubuntu mysql packages, you can login with user debian-sys-maint , which has all the expected privileges, the password is stored in the file /etc/mysql/debian.cnf

Answers provided here did not seem to work for me, the trick turned out to be: ALTER USER ‘root’@’localhost’ IDENTIFIED WITH mysql_native_password BY ‘test’;

Kuro Neko's user avatar

System:

  • CentOS Linux 7
  • mysql Ver 14.14 Distrib 5.7.25

Procedure:

Open two shell sessions, logging in to one as the Linux root user and the other as a nonroot user with access to the mysql command.

In your root session, stop the normal mysqld listener and start a listener which bypasses password authentication (note: this is a significant security risk as anyone with access to the mysql command may access your databases without a password. You may want to close active shell sessions and/or disable shell access before doing this):

# systemctl stop mysqld
# /usr/sbin/mysqld —skip-grant-tables -u mysql &

In your nonroot session, log in to mysql and set the mysql root password:

$ mysql
mysql> flush privileges;
Query OK, 0 rows affected (0.00 sec)

mysql> SET PASSWORD FOR ‘root’@’localhost’ = PASSWORD(‘MyNewPass’);
Query OK, 0 rows affected, 1 warning (0.01 sec)

In your root session, kill the passwordless instance of mysqld and restore the normal mysqld listener to service:

# kill %1
# systemctl start mysqld

In your nonroot session, test the new root password you configured above:

$ mysql -u root -p
Enter password:
Welcome to the MySQL monitor. Commands end with ; or \g.
.
mysql>

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *