Mysql-server 安装

更新软件包

1
sudo apt update

安装

1
sudo apt install mysql-server

查看 Mysql 版本

1
mysql --version

查看服务状态

1
service mysql status

配置

此时,mysql 客户端已经作为服务器的依赖安装到本地,故可以通过命令行登录服务器。Mysql 8.0,root 用户默认通过 auth_socket 插件授权,而 auth_socket 插件通过 Unix socket 文件来验证所有连接到 localhost 的用户。这意味着你不能以用户–密码的方式,登录 root 账户。通过指令以 root 身份登录

1
sudo mysql

查看 user 表

1
2
use mysql;
select user, host,plugin from user;

修改密码

1
2
3
4
5
alter user 'root'@'localhost' identified with mysql_native_password by '密码';

flush privileges;

exit;

通过密码登录

1
mysql -uroot -p

增强数据库服务的安全性

1
sudo mysql_secure_installation
  1. 输入 Y 继续
  2. 设置 Root 用户密码, 并反馈当前密码强度, 询问是否确认密码
  3. 询问三个问题, 并根据提供的答案来设置系统的安全性
  4. 是否关删除匿名测试用户的信息。
  5. 是否禁止远程root登录。只允许本地登录root用户,并拒绝远程连接。
  6. 是否删除 test 数据库。
  7. 确认, 并生效配置

远程链接

1
2
3
4
#MySQL8.0!!!
sudo vim /etc/mysql/mysql.conf.d/mysqld.cnf
#MySQL5.7!!!
sudo vim /etc/my.cnf

![[Pasted image 20241021205742.png]]

重启数据库

1
sudo service mysql restart

登录 Mysql 后执行

1
2
3
4
5
6
7
8
9
10
11
use mysql;
update user set host='%' where user='root';
flush privileges;

#MySQL8.0执行这行
GRANT ALL PRIVILEGES ON *.* TO 'root'@'%' WITH GRANT OPTION;
#MySQL5.7执行这行
GRANT ALL PRIVILEGES ON *.* TO 'root'@'%' IDENTIFIED BY '密码' WITH GRANT OPTION;

flush privileges;

卸载

1
2
3
4
5
6
7
sudo apt purge mysql-* # mysql后用tab补全,把所有与mysql相关的卸载

sudo rm -rf /etc/mysql/ /var/lib/mysql

sudo apt autoremove

sudo apt autoclean

忘记密码

修改配置文件,在mysqld 后添加 skip-grant-tables (登录时跳过权限检查):

1
2
3
4
#MySQL8.0!!!
sudo vim /etc/mysql/mysql.conf.d/mysqld.cnf
#MySQL5.7!!!
sudo vim /etc/my.cnf

![[Pasted image 20241022134540.png]]

1
2
sudo service mysql restart
mysql

修改密码

![[Pasted image 20241022140428.png]]

Mysql 8.0

1
2
3
4
5
6
7
8
use mysql; 
#必须先将authentication_string置为空!
update user set authentication_string='' where user='root';

flush privileges;
#设置新密码
ALTER user 'root'@'%' IDENTIFIED BY '新密码';

Mysql 5.7

1
2
use mysql; 
update user set authentication_string = password('新密码') where user = 'root';

最后记得删除配置文件中的 skip-grant-tables 并重启服务,否则会影响远程连接!

ERROR 1819 (HY000): Your password does not satisfy the current policy requirements

1
SHOW VARIABLES LIKE 'validate_password%';

![[Pasted image 20241022135723.png]]

修改

1
2
set global validate_password.policy=0
set global validate_password.length=1;

最后在修改密码

1
alter user 'root'@'%' identified by 'root';