Linux error 1045 access denied

Access denied for user ‘root’@’localhost’ (using password: YES) after new installation on Ubuntu

TL;DR: To access newer versions of mysql/mariadb as the root user, after a new install, you need to be in a root shell (ie sudo mysql -u root , or mysql -u root inside a shell started by su — or sudo -i first)

Having just done the same upgrade, on Ubuntu, I had the same issue.

sudo /usr/bin/mysql_secure_installation 

Would accept my password, and allow me to set it, but I couldn’t log in as root via the mysql client

I had to start mariadb with

sudo mysqld_safe --skip-grant-tables 

to get access as root, whilst all the other users could still access fine.

Looking at the mysql.user table I noticed for root the plugin column is set to unix_socket whereas all other users it is set to ‘mysql_native_password’. A quick look at this page: https://mariadb.com/kb/en/mariadb/unix_socket-authentication-plugin/ explains that the Unix Socket enables logging in by matching uid of the process running the client with that of the user in the mysql.user table. In other words to access mariadb as root you have to be logged in as root.

Sure enough restarting my mariadb daemon with authentication required I can login as root with

Having done this I thought about how to access without having to do the sudo, which is just a matter of running these mysql queries

GRANT ALL PRIVILEGES on *.* to 'root'@'localhost' IDENTIFIED BY ''; FLUSH PRIVILEGES; 

(replacing with your desired mysql root password). This enabled password logins for the root user.

Alternatively running the mysql query:

UPDATE mysql.user SET plugin = 'mysql_native_password' WHERE user = 'root' AND plugin = 'unix_socket'; FLUSH PRIVILEGES; 

Will change the root account to use password login without changing the password, but this may leave you with a mysql/mariadb install with no root password on it.

After either of these you need to restarting mysql/mariadb:

sudo service mysql restart 

And voila I had access from my personal account via mysql -u root -p

PLEASE NOTE THAT DOING THIS IS REDUCING SECURITY Presumably the MariaDB developers have opted to have root access work like this for a good reason.

Читайте также:  Astra linux orel sources list

Thinking about it I’m quite happy to have to sudo mysql -u root -p so I’m switching back to that, but I thought I’d post my solution as I couldn’t find one elsewhere.

Источник

ERROR 1045 (28000): Access denied for user ‘root’@’localhost’ (using password: NO): что делать?

Решил, что пора изучать БД, и споткнулся, еще даже не сумев запустить БД.

В видеокурсе показано было следующее:
sudo apt-get install mysql-server
mysql -u root -p

Автор ввел пароль и спокойно зашел. Я получил ошибку, указанную в заголовке.
Начал гуглить и наткнулся примерно на следующие советы:
Совет 1: заходить через mysql -u root, то есть не добавлять -p. Не помогло, ошибка прежняя.
Совет 2: mysqladmin -u root password [newpassword]. То же самое.

Сложный 9 комментариев

ololopishpishrealne

Konstantin18ko

Konstantin18ko

Konstantin18ko

Konstantin Malyarov: он его даже не просит при таком запросе:

anton@anton-X451CA:~/studyDB$ mysql -h localhost -u root
ERROR 1045 (28000): Access denied for user ‘root’@’localhost’ (using password: NO)

Konstantin18ko

Тут два варианта, ИМХО.
1) Вы что-то не так поняли из курса:
2) Составитель курса что-то упустил.
В любом случае или стоило бы сюда ссылку кинуть на этот курс или писать составителю.

По проблеме. Сервер mysql пишет вам, что пользователю ‘root’ доступ закрыт. Как мне кажется, нужно вначале создать бд, применить схему и там создастся пользователь, с данными которого вы подключитесь к бд. А слова «Using password: NO» означает лишь, что пароль и не использовался.

Ну вот у меня та же проблема.
$mysql
ERROR 1045 (28000): Access denied for user ‘rni’@’localhost’ (using password: NO)
А так пожалуйста
$ sudo mysql
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 10
Server version: 8.0.32-0ubuntu0.22.04.2 (Ubuntu)

А хотелось бы просто заходить без sudo

Это может быть, если пароль не был задан при установке.

Порядок действий для установки/смены пароля root в mysql следующий:

1. Остановить mysql:
sudo service mysql stop

2. Запустить сервис со следующими параметрами:
sudo mysqld —skip-grant-tables —user=root

Если выдал ошибку то в файле /etc/mysql/mysql.conf.d/mysqld.cnf в секцию [mysqld] добавить строчку skip-grant-tables и выполнить sudo service mysql restart

3. После этого подключиться к mysql командой:
mysql -u root

4. Обновить пароль root’a:

UPDATE mysql.user SET authentication_string=PASSWORD(''), plugin='mysql_native_password' WHERE User='root' AND Host='localhost'; FLUSH PRIVILEGES;

5. И перезапустить сервис:
sudo service mysql restart
Если на шаге 2 вы добавляли skip-grant-tables в /etc/mysql/mysql.conf.d/mysqld.cnf — удалить эту строчку.

Читайте также:  Централизованное хранение логов linux

fapchat

ERROR 2002 (HY000): Can’t connect to local MySQL server through socket ‘/var/run/mysqld/mysqld.sock’ (2)

Я не запускал команду
sudo mysqld —skip-grant-tables —user=root
вручную отредактировал файл /etc/mysql/mysql.conf.d/mysqld.cnf , добавив skip-grant-tables
и затем просто запустил
mysqld -u root

fapchat, У меня тоже такое было. Повторил сначала, предварительно добавив строчку skip-grant-tables в /etc/mysql/mysql.conf.d/mysqld.cnf

Пароль по умолчанию пустой.
Возможно, вы неправильно набрали команду. Скопируйте именно эту: mysql -u root -p . На запрос пароля надо просто нажать Enter.

Попробуйте запустить mysql_secure_installation .

Если все равно не пускает — поищите пароль в логе: sudo grep ‘temporary password’ /var/log/mysqld.log .

Если и этот вариант не подошел — возможно, устанавливаете из какого-то левого репозитория. Удалите sudo apt-get purge mysql* , выключите левые репозитории и установите заново sudo apt-get install mysql-server .

Почему-то не получается отредактировать предыдущий комментарий.
Ни одна из команд не помогла. первая дала такой же результат, mysql_secure_installation выдала следующее:
anton@anton-X451CA:~/studyDB$ mysql_secure_installation
Securing the MySQL server deployment.
Enter password for user root:

В итоге та же самая ошибка. Оставлял поле пароля пустым, без толку.

Идаже удалить вашей командой не получается:
anton@anton-X451CA:~/studyDB$ sudo apt-get purge mysql*
Чтение списков пакетов… Готово
Построение дерева зависимостей
Чтение информации о состоянии… Готово
E: Не удалось найти пакет mysqladmin

Удалил командой sudo apt-get remove mysql-server и поставил заново тот же пакет. Результат тот же.

Источник

MySQL — ERROR 1045 — Access denied

I have tried resetting the password without any luck using this HowTo. I have uninstalled mysql completley and reinstalled but I still get asked for a password. I have no idea why this is the case! Can someone please help me get a default install of MySQL.

Environment

EDIT

To all those that would like to save themselves a few hours of «blood coughing» — when you uninstall MySQl completely delete everything that is left behind. If you don’t do this, it will never be a FRESH install.

7 Answers 7

If you actually have set a root password and you’ve just lost/forgotten it:

  1. Stop MySQL
  2. Restart it manually with the skip-grant-tables option: mysqld_safe —skip-grant-tables
  3. Now, open a new terminal window and run the MySQL client: mysql -u root
  4. Reset the root password manually with this MySQL command: UPDATE mysql.user SET Password=PASSWORD(‘password’) WHERE User=’root’; If you are using MySQL 5.7 (check using mysql —version in the Terminal) then the command is:
UPDATE mysql.user SET authentication_string=PASSWORD('password') WHERE User='root'; 

(Maybe this isn’t what you need, Abs, but I figure it could be useful for people stumbling across this question in the future)

In my case, mysql 5.5 installation on windows 7 didn’t prompt for password and I had to use the solution above. Please note that you need to shutdown mysqld using ‘mysqladmin -u root -p shutdown’ because Ctrl-C does not stop mysqld and probably you don’t want to kill it.

For MySQL 5.7, there is no password column in the user table. So replace, step number 4. with the code: UPDATE mysql.user SET authentication_string=PASSWORD(‘password’) WHERE User=’root’;

This works but only as long as you do it each time yo start mysql. If I reboot the computer the same error happens again and I have to do all this all over again. I was wondering if there is a permanent fix.

Try connecting without any password:

I believe the initial default is no password for the root account (which should obviously be changed as soon as possible).

use this command to check the possible output

mysql> select user,host,password from mysql.user; 
mysql> select user,host,password from mysql.user; +-------+-----------------------+-------------------------------------------+ | user | host | password | +-------+-----------------------+-------------------------------------------+ | root | localhost | *8232A1298A49F710DBEE0B330C42EEC825D4190A | | root | localhost.localdomain | *8232A1298A49F710DBEE0B330C42EEC825D4190A | | root | 127.0.0.1 | *8232A1298A49F710DBEE0B330C42EEC825D4190A | | admin | localhost | *2470C0C06DEE42FD1618BB99005ADCA2EC9D1E19 | | admin | % | | +-------+-----------------------+-------------------------------------------+ 5 rows in set (0.00 sec) 
  1. In this user admin will not be allowed to login from another host though you have granted permission. the reason is that user admin is not identified by any password.
  2. Grant the user admin with password using GRANT command once again
mysql> GRANT ALL PRIVILEGES ON *.* TO 'admin'@'%' IDENTIFIED by 'password' 

then check the GRANT LIST the out put will be like his

mysql> select user,host,password from mysql.user; +-------+-----------------------+-------------------------------------------+ | user | host | password | +-------+-----------------------+-------------------------------------------+ | root | localhost | *8232A1298A49F710DBEE0B330C42EEC825D4190A | | root | localhost.localdomain | *8232A1298A49F710DBEE0B330C42EEC825D4190A | | root | 127.0.0.1 | *8232A1298A49F710DBEE0B330C42EEC825D4190A | | admin | localhost | *2470C0C06DEE42FD1618BB99005ADCA2EC9D1E19 | | admin | % | *2470C0C06DEE42FD1618BB99005ADCA2EC9D1E19 | +-------+-----------------------+-------------------------------------------+ 5 rows in set (0.00 sec) 

if the desired user for example user ‘admin’ is need to be allowed login then use once GRANT command and execute the command.

Now the user should be allowed to login.

Источник

Оцените статью
Adblock
detector