Ubuntu安装MySQL密码初始化问题

Ubuntu下安装MySQL之后竟然没有密码设定

在Ubuntu上使用sudo apt-get install mysql-server命令安装MySQL以后,安装过程中没有提示输入密码。然后使用mysql -u root -p 进行登录,然后要求输入密码,可是不管怎么输入,都提示密码错误,那怎么解决呢?
# 安装mysql
$ sudo apt-get update
$ sudo apt-get install mysql-server

# 安装过程并没有提示输入root的密码
# 安装玩尝试登录,却显示错误
$ mysql -u root -p
Enter password: 
ERROR 1698 (28000): Access denied for user 'root'@'localhost'
原来mysql-server在安装的时候会自动生成admin级别的用户名和密码
解决方案如下:
  1. 打开/etc/mysql/debian.cnf文件,在这个文件中有系统默认给我们分配的用户名和密码,通过这个密码就可以直接对MySQL进行操作了。
    $ sudo cat /etc/mysql/debian.cnf 
    [sudo] password for libredesign: 
    # Automatically generated for Debian scripts. DO NOT TOUCH!
    [client]
    host     = localhost
    user     = debian-sys-maint
    password = 
    socket   = /var/run/mysqld/mysqld.sock
    [mysql_upgrade]
    host     = localhost
    user     = debian-sys-maint
    password = 
    socket   = /var/run/mysqld/mysqld.sock
    
  2. 以debian-sys-maint为用户名登录,密码就是debian.cnf里那个。使用mysql -u debian-sys-maint -p 进行登录。
  3. 进入mysql之后修改MySQL的密码,具体的操作如下用命令:set password for 'root'@'localhost' = password('yourpass');当修改之后就可应正常对MySQL进行操作了。
但是等等,当我这样修改完root的密码之后,发现再次尝试登录还是无法以root权限登录mysql,甚至重启mysql服务也不行
$ sudo service mysql stop
$ sudo service mysql start
$ mysql -u root -p
Enter password: 
ERROR 1698 (28000): Access denied for user 'root'@'localhost'
这又是为什么呢?

修改了root密码为什么还是不能登录?

解决步骤:
用第一步的方法,以debian-sys-maint用户登录进mysql
查看一下user表,错误的起因就是在这里, root的plugin被修改成了auth_socket,用密码登陆的plugin应该是mysql_native_password
mysql> select user, plugin from mysql.user;
+-----------+-----------------------+
| user      | plugin                |
+-----------+-----------------------+
| root      | auth_socket           |
| mysql.sys | mysql_native_password |
| dev       | mysql_native_password |
+-----------+-----------------------+
3 rows in set (0.01 sec)
关于auth_socket,在官方有说明,反正现在暂时不用它, 那就把这里改了。
mysql> update mysql.user set authentication_string=PASSWORD('newPwd'), plugin='mysql_native_password' where user='root';
Query OK, 1 row affected, 1 warning (0.00 sec)
Rows matched: 1  Changed: 1  Warnings: 1

mysql> flush privileges;
Query OK, 0 rows affected (0.00 sec)
重启服务,问题就解决了
$ sudo service mysql stop
...
 * MySQL Community Server 5.7.23 is stopped
$ sudo service mysql start
..
 * MySQL Community Server 5.7.23 is started
$ mysql -u root -p
Enter password: 
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 4
Server version: 5.7.23-0ubuntu0.18.04.1 (Ubuntu)

无root密码以安全模式启动MySQL

当然,如果没有前面提到的debian-sys-maint的用户和权限,还有另外一种方式绕过root密码验证的方式登录mysql的,那就是以安全模式启动MySQL
解决步骤:
停止mysql服务
$ sudo service mysql stop
以安全模式启动MySQL
$ sudo mysqld_safe --skip-grant-tables &
MySQL启动之后就可以不用密码登陆了
$ mysql -u root
Welcome to the MySQL monitor. Commands end with ; or \g. Your MySQL connection id is 4 Server version: 5.7.23-0ubuntu0.18.04.1 (Ubuntu)

Comments

Popular posts from this blog

“垃圾回收”之草稿合集

自律

恍惚了一下