MySQL 设置密码
大约 3 分钟
MySQL 设置密码
一、修改配置文件
当我们不知道 MySQL 的默认密码时,需要连接就要使用这招;
在 MySQL 的配置文件中加入如下的内容,一般配置文件在 /ect/my.conf
[mysqld]
...
skip-grant-tables
此时我们使用命令,然后直接回车就能进入 MySQL 终端
./mysql -uroot
二、修改密码命令
修改密码其实很简单只需要一个命令就行:
ALTER USER 'root'@'localhost' IDENTIFIED BY 'you_password';
三、实践出真知
知道了如何修改密码,那我们进行一下实操
[root@VM-0-8-centos bin]# systemctl start mysqld.service
[root@VM-0-8-centos bin]#
[root@VM-0-8-centos bin]# ./mysql -uroot
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 2
Server version: 5.7.25 Source distribution
Copyright (c) 2000, 2019, Oracle and/or its affiliates. All rights reserved.
Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
mysql> ALTER USER 'root'@'localhost' IDENTIFIED BY 'you_password';
ERROR 1290 (HY000): The MySQL server is running with the --skip-grant-tables option so it cannot execute this statement
结果并不理想,我们先启动 MySQL 服务,然后再进入终端执行命令,结果报错了,大意是:MySQL 服务正在使用,无法执行。
于是我们把 MySQL 服务停掉试试
[root@VM-0-8-centos bin]# systemctl stop mysqld
[root@VM-0-8-centos bin]#
[root@VM-0-8-centos bin]# ./mysql -uroot
ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/tmp/mysql.sock' (2)
可想而知,停掉之后,服务连接不上。
那么岂不是陷入了死循环,启动执行不了,停止无法进入终端...
解决办法
解决办法很简单,我们只需要进入终端之后执行命令
FLUSH PRIVILEGES;
然后再执行修改密码,修改完毕之后再 FLUSH PRIVILEGES; 即可
密码修改完毕之后把配置文件修改回去,再重启 MySQL 服务,使用我们刚刚设置的密码登录试试,结果是可以的。
四、客户端工具连接
于是我们迫不及待的想使用客户端工具,如:navicat 连接试试。
结果又又又报错了
1130 - Host 'xx.xx.xx.xx' is not allowed to connect to this MySQL server
看样子是我们这个 IP 不能连接,那要怎么办,查阅资料发现原理要修改权限。
修改权限:
-- 进入mysql命令行
-- 新用户示例:
CREATE USER 'my_user'@'%' IDENTIFIED BY 'my_password';
GRANT ALL PRIVILEGES ON *.* TO 'my_user'@'%' IDENTIFIED BY 'my_password' WITH GRANT OPTION;
FLUSH PRIVILEGES;
-- root用户示例:
GRANT ALL PRIVILEGES ON *.* TO root@'%' IDENTIFIED BY 'you_password' WITH GRANT OPTION;
FLUSH PRIVILEGES;
修改完毕之后再使用工具发现已经可以连接上了。
注意
如果你是云厂商的服务器,是需要去对应的控制台开放安全组的。
如果你有开启防火墙,需要开放防火墙端口。
非本机连接需要开放全 0 端口监听
开放防火墙端口:
sudo firewall-cmd --zone=public --add-port=3306/tcp --permanent
sudo firewall-cmd --reload
开放全 0 监听
修改配置文件
[mysqld]
bind-address = 0.0.0.0
# 确保配置文件中的 skip-networking 被注释
五、总结
先修改配置文件,跳过密码验证
修改密码前后都要执行
FLUSH PRIVILEGES;客户端连接需要修改权限
注意云厂商的安全组和防火墙等