# Главная
# О библиотеке

# Выбор дистрибутива
преимущества Linux/UNIX | основные дистрибутивы | серверный Linux | BSD | LiveCDs | прочее

# Установка и удаление программ
общие вопросы | каталоги софта | специальные случаи

# Настройка и работа
установка, загрузчики | настройка Linux | консоль | файловые системы | процессы | шеллы, русификация, коммандеры | виртуальные машины, эмуляторы

# X Window и оконные менеджеры
настройка X Window | GNOME | KDE | IceWM и др.

# Работа с текстами
редакторы | офис | шрифты, кодировки и русификация | преобразования текстовых файлов | LaTeX, SGML и др. | словари

# Графика
GIMP | фото | обработка изображений | форматы графических файлов

# Сети, администрирование
общие вопросы | Dialup & PPP | брандмауэры | маршрутизация | работа в Windows-сетях | веб-серверы | Apache | прокси-серверы | сетевая печать | прочее

# Программирование
GCC & GNU make | программирование в UNIX | графические библиотеки | Tcl | Perl | PHP | Java & C# | СУБД | CVS | прочее

# Ядро
# Мультимедиа
# Интернет
# Почта
# Безопасность
# Железо
# Разное

# Linux HowTo (как сделать)
# Книги и руководства
# Материалы на английском языке


MySQL The World's Most Popular Open Source Database # Online shop | Site map |  
CompanyProductsSupport & ConsultingTraining & CertificationDownloadsDocumentation
  BooksArticlesMailing ListsPresentationsOther Sites  
Search the MySQL manual:
MySQL Manual
  • A Проблемы и распространенные ошибки
    • A.4 Вопросы, связанные с администрированием
      • A.4.1 Что делать, если работа MySQL сопровождается постоянными сбоями
      • A.4.2 Как переустановить забытый пароль пользователя root
      • A.4.3 Как MySQL реагирует на переполнение диска
      • A.4.4 Где MySQL хранит временные файлы
      • A.4.5 Как защитить или изменить сокет-файл MySQL `/tmp/mysql.sock'
      • A.4.6 Проблемы с часовыми поясами

Buy this Reference Manual in softcover from Barnes & Noble!

MySQL Reference Manual
Previous / Next / Up / Table of Contents

A.4.2 Как переустановить забытый пароль пользователя root

Если для MySQL пароль пользователя root никогда не устанавливался, то для соединения с сервером в качестве пользователя root пароль не потребуется. Рекомендуется всегда устанавливать пароль для каждого пользователя (see section 4.2.2 Как обезопасить MySQL от хакеров).

Если вы забыли установленный для root пароль, то новый пароль можно задать при помощи следующей процедуры:

  1. Остановите сервер mysqld; для этого нужно послать kill (но не kill -9) серверу mysqld. Номер процесса хранится в файле `.pid', обычно расположенном в каталоге баз данных MySQL:
    shell> kill `cat /mysql-data-directory/hostname.pid`
    
    Чтобы выполнить эту команду, необходимо быть либо Unix-пользователем root, либо пользователем, под которым работает mysqld.
  2. Перезапустите mysqld с опцией --skip-grant-tables.
  3. Установите новый пароль с помощью команды mysqladmin password:
    shell> mysqladmin -u root password 'mynewpassword'
    
  4. Теперь можно либо просто остановить mysqld и заново запустить его обычным способом, либо просто загрузить таблицы привилегий посредством:
    shell> mysqladmin -h hostname flush-privileges
    
  5. После этого можно будет соединяться, пользуясь новым паролем.

Есть и другой способ установки нового пароля - с помощью клиента mysql:

    Остановите mysqld и перезапустите его с опцией --skip-grant-tables, как было описано ранее.
  1. Соединитесь с сервером mysqld посредством:
    shell> mysql -u root mysql
    
  2. Выполните следующие команды из клиента mysql:
    mysql> UPDATE user SET Password=PASSWORD('mynewpassword')
        -> WHERE User='root';
    mysql> FLUSH PRIVILEGES;
    
  3. После этого можно будет соединяться по новому паролю.
  4. Остановите mysqld и запустите его заново, как обычно.

User Comments

Posted by Marc Wiz on Thursday August 22 2002, @7:53am[Delete] [Edit]

I tried to use the mysqladmin of changing the root
password and it did not work. I kept getting
errors about not having permissions to access the
database.

Using the mysql client method of changing the root
password worked.

Posted by [email protected] on Friday August 23 2002, @3:21pm[Delete] [Edit]

same problem here, using redhat 7.3 and rpm
installation. any suggestions?

Posted by [name withheld] on Tuesday September 17 2002, @7:36pm[Delete] [Edit]

I ran into the same trouble on RH7.3 attempting to
use the mysqladmin means. I was able to
successfully change mine using the msql client
alternative means.

Posted by [email protected] on Monday September 23 2002, @8:20pm[Delete] [Edit]

same problem on a cobalt raq, the mysql client way
worked

Posted by Whit Blauvelt on Wednesday October 9 2002, @11:34am[Delete] [Edit]

The directions here are not adequate to 4.04-beta.

After upgrading, 4.040-beta worked fine through
several reboots. But on the last reboot it somehow
lost the root password. Trying to use these
instructions to reset the root password results in:

# mysql/bin/mysqld --skip-grant-tables
Fatal error: Please read "Security" section of the
manual to find out how to run mysqld as root!
021009 14:26:29 Aborting

And that's after figuring out that it can't even
show the error message unless you try to invoke
mysqld from /usr/local rather than, say,
/usr/local/msyql. First off, corrupting the root
password is a bad thing, even for a beta. Second,
the recovery instructions in the manual should be
complete, not sketchy. Third, having error
messages that depend on your being in a
nonstandard place in the path even to see them,
rather than an error message about not finding the
error messages ... should this beta be an alpha?

Posted by Whit Blauvelt on Wednesday October 9 2002, @11:47am[Delete] [Edit]

Okay, so I then start mysqld with --user="mysql",
which seems to work, but:

mysqladmin -u root password 'somepass'
mysqladmin: unable to change password; error: 'You
must have privileges to update tables in the mysql
database to be able to change passwords for others'

So root doesn't have privileges to update tables,
and root is an "other"?

Posted by Whit Blauvelt on Wednesday October 9 2002, @11:56am[Delete] [Edit]

The "Alternate method" above does successfully
correct the root password corruption (however that
happened!).

Posted by Whit Blauvelt on Wednesday October 9 2002, @12:13pm[Delete] [Edit]

Nope. Not fixed. Reboot and it's broken again.

Posted by Whit Blauvelt on Wednesday October 9 2002, @12:33pm[Delete] [Edit]

Okay, mysqld_safe seems to start it in a broken
state, re the root password. Also, the mysql init
script (Red Hat 6.0) starts it in a broken state.
But going to /usr/local and invoking
mysql/bin/mysqld --user="mysql" & seems to work
okay - unless the failures I'm seeing reflect
something random. Having mysql insist on being in
/usr/local when starting is nasty (hmm, maybe
there's some flag to have it find it's error files
- but it shouldn't be a fatal error not to find them).

Posted by Sakshale eQuorian on Wednesday December 18 2002, @5:27pm[Delete] [Edit]

mysqld Ver 3.23.40, the following command line
succesfully starts the daemon without the grant tables..

mysqld --skip-grant-tables --user="mysql"

However, using mysqladmin to change the root
password failed. Using the mysql client method to
manually add the password worked.

Posted by Stefan Wimmer on Wednesday November 13 2002, @9:42am[Delete] [Edit]

Environment RH7.2 MySQL 4.04 ran into the
same problems as described above concerning
restarting mysqld with --skip-grant-tables.
For me this was the solution: mysqld --skip-
grant-tables user="root"
Only then I was able to log on to the client as
root.
Greets, Stefan

Posted by [name withheld] on Wednesday November 13 2002, @7:07pm[Delete] [Edit]

Any help for a Windows user with this issue?

Posted by [name withheld] on Wednesday November 27 2002, @4:06pm[Delete] [Edit]

Mysql 4.0.4 Redhat 7.3
I had a similar error, and none of these fixes worked,
I had to run the safe demon in order to get in to
update my password. I wont forget it again!!!

safe_mysqld --skip-grant-tables &

mysql

use mysql;

update user set password = password('.......') where
user = 'root' and host='localhost';

Posted by Alexi Papaleonardos on Monday December 2 2002, @9:16am[Delete] [Edit]

I found that the second technique listed, using mysql
client, worked when the first one (using mysqladmin)
failed with the 'You must have privileges to update
tables in the mysql database to be able to change
passwords for others'. (FreeBSD 4.7-RELEASE,
mysql 3.23.52).

Posted by [name withheld] on Thursday January 16 2003, @8:22am[Delete] [Edit]

For me the database directory was not good, so I suggest doing sonthing like : mysqld --skip-grant-tables --user=root --datadir=/var/lib/mysql/

Indeed my default datadir was /var/, and it was useless trying to connect to the database 'mysql' where I had to edit the passwords...

So I suggest using the solution with mysql client, so that you can fix problems due to wrong default settings.
May this comment helps you!

Posted by . . on Thursday January 23 2003, @10:38am[Delete] [Edit]

How to Reset a Forgotten Root Password on Win2000 ???

Delete mysql dir under mysql/data.
Install the same Mysql version on other PC
Copy the fresh mysql dir.
Restart win.

Posted by [name withheld] on Tuesday January 28 2003, @9:13am[Delete] [Edit]

let me show the way of reset root password;
based on windows 2000 pro.

at first, stop mysql service
open cmd console,
move to c:/mysql/bin
type below...

c:\mysql\bin>start mysqld -Sg (enter :))

c:\mysql\bin>



it's done... root password has been cleared :)

good job.

Posted by Michael Michels on Tuesday February 11 2003, @7:31am[Delete] [Edit]

It seems that you can also change the root password by starting the 'mysqld ... --skip-grant-tables ...' parallel to the running one. Just override the values from '/etc/my.cnf' with command line options like:
--port=42000
--socket=/tmp/foobar.sock
--pid-file=/tmp/foobar.pid
and then connect to it, do your changes and kill it.
It worked for me ;0)

Posted by omar yousif on Saturday February 15 2003, @7:12pm[Delete] [Edit]

Im using OSX I have MySQL installed but I cant set the password.


when I try
kill `cat /mysql-data-directory/hostname.pid`

cat: /mysql-data-directory/hostname.pid: No such file or directory

/usr/local/bin/mysqladmin -u root password jahova

I get

./bin/mysqladmin: connect to server at 'localhost' failed
error: 'Access denied for user: 'root@localhost' (Using password: NO)'

Any ideas. I really need to get this setup.

Thanks in advance all you gurus.

Posted by marcel on Tuesday February 18 2003, @5:15am[Delete] [Edit]

I tried to change root password but when I try to start mysqld whit --skip-grant-tables I receive this useless msg:"Fatal error: Please read "Security" section of the manual to find out how to run mysqld as root!
030218 13:36:00 Aborting " .But it work fine with :
/usr/libexec/mysqld -Sg --user="mysql".And only alternate method whit mysql client do the job.Thanks fly to other for posting comment

Posted by Wolf Schweitzer on Wednesday February 26 2003, @12:51pm[Delete] [Edit]

On Mac OS X, you can install MySQL following any of these guidelines:

Good starting points:

www.macosxhints.com/article.php?story=20010402202522315
www.entropy.ch

Once the ./mysql_install_db script is run, and once the MySQL has been started with the command safe_mysqld & it is safe to assume your MySQL is actually running, but what next? The privileges problem needs to be addressed.

Follow the guidelines on macosxhints, particularly, where it says this, which I repeat somewhat similarly:

Type the following as 'root':

> mysql

Then, inside MySQL, type after the m> prompt, and include the '' quotes around the password:

m> GRANT ALL PRIVILEGES ON *.* TO yourusername@localhost IDENTIFIED BY 'whateverpasswordyouwant';
m> quit

From there, I suggest you continue setting up MySQL using pHpMyAdmin, if you have pHp set up and running. It is better than MacSQL, a Mac OS X program, if you want to remotely administrate this via another computer on the same network.

pHpMyAdmin is a very neat utility that helps you solve privileges problems in an efficient way.

Before you start it, enter the correct settings into the 'config.inc.php' file! That's the secret. From there, you can set/grant/delete all privileges with the on-screen gui which is a bit more intuitive than using command line commands.

Starting points to look for the software mentioned:

pHp package for Mac OS X - www.entropy.ch
pHpMyadmin- www.sourceforge.net
MacSQL- www.versiontracker.com

Wolf Schweitzer, www.swisswuff.ch

Add your own comment.

Top / Previous / Next / Up / Table of Contents
# MySQL.com home | Site map | Contact us | Press | Jobs | Privacy policy | Trademark info | © 1995-2003 MySQL AB. All rights reserved.