Ubuntu 22 开启 root 登录并设置密码完整教程
Ubuntu 22 开启 root 登录并设置密码完整教程
很多云服务器:
- Ubuntu 22
- AWS
- Oracle Cloud
- 阿里云
- 腾讯云
默认:
1 | 禁止 root 远程登录 |
只能:
1 | 普通用户 + sudo |
虽然更安全:
但很多时候:
1 | 运维操作不方便 |
本篇文章教你:
- Ubuntu 开启 root
- 设置 root 密码
- SSH 允许 root 登录
- 开启密码登录
- 解决 SSH 禁止问题
为什么 Ubuntu 默认禁用 root?
Ubuntu 默认:
1 | 更强调安全性 |
所以:
- root 默认没有密码
- SSH 禁止 root
- SSH 禁止密码登录
只能:
1 | 普通用户 + sudo |
一、设置 root 密码
执行:
1 | passwd root |
然后:
1 | 输入两次密码 |
例如:
1 | New password: |
设置成功后
会看到:
1 | password updated successfully |
说明:
1 | root 密码设置成功 |
二、开启 SSH Root 登录
编辑:
1 | /etc/ssh/sshd_config |
最简单方式:
直接执行:
1 | sed -i 's/^#\?PermitRootLogin.*/PermitRootLogin yes/g' /etc/ssh/sshd_config |
什么是 PermitRootLogin?
作用:
1 | 允许 root SSH 登录 |
默认:
1 | 可能是 prohibit-password |
或者:
1 | no |
三、开启密码登录
Ubuntu 很多服务器:
1 | 默认禁止密码登录 |
执行:
1 | sed -i 's/^#\?PasswordAuthentication.*/PasswordAuthentication yes/g' /etc/ssh/sshd_config |
PasswordAuthentication 是什么?
作用:
1 | 允许 SSH 使用密码登录 |
否则:
1 | 只能密钥登录 |
四、兼容 Ubuntu 22 新版配置
Ubuntu 22:
1 | 很多 SSH 配置拆分到了 sshd_config.d |
所以:
1 | 仅修改主配置文件可能无效 |
继续执行:
1 | sed -i 's/PasswordAuthentication no/PasswordAuthentication yes/g' /etc/ssh/sshd_config.d/*.conf 2>/dev/null |
再执行:
1 | sed -i 's/PermitRootLogin.*/PermitRootLogin yes/g' /etc/ssh/sshd_config.d/*.conf 2>/dev/null |
为什么需要 2>/dev/null?
作用:
1 | 忽略不存在文件报错 |
更安全。
五、重新设置 root 密码(推荐)
再次执行:
1 | passwd root |
确保:
1 | root 密码正确 |
六、重启 SSH 服务
执行:
1 | systemctl restart ssh |
七、测试 root 登录
使用:
1 | Xshell |
1 | FinalShell |
1 | Termius |
1 | MobaXterm |
连接:
| 配置 | 内容 |
|---|---|
| IP | 服务器公网 IP |
| 用户名 | root |
| 密码 | root 密码 |
八、查看 SSH 是否开启成功
执行:
1 | ss -tunlp | grep ssh |
九、常见问题
1. Permission denied
原因:
- 密码错误
- root 未开启
- SSH 未重启
2. 还是无法 root 登录
检查:
1 | cat /etc/ssh/sshd_config |
确认:
1 | PermitRootLogin yes |
3. PasswordAuthentication 不生效
Ubuntu 22:
1 | 可能被 sshd_config.d 覆盖 |
所以:
1 | 必须同时修改 .d 配置 |
4. 云服务器无法连接
检查:
- 安全组
- 防火墙
- 22 端口
十、防火墙开放 SSH
Ubuntu:
1 | sudo ufw allow 22/tcp |
十一、查看 SSH 状态
执行:
1 | systemctl status ssh |
十二、推荐安全方案
生产环境:
1 | 不推荐长期开放 root 密码登录 |
建议:
- 使用 SSH Key
- 禁止密码登录
- 限制 IP
- 使用 Fail2ban
推荐生产环境配置
| 功能 | 推荐 |
|---|---|
| root 密码登录 | 不推荐 |
| SSH Key | 推荐 |
| Fail2ban | 推荐 |
| IP 白名单 | 推荐 |
十三、如何关闭 root 登录?
修改:
1 | PermitRootLogin no |
然后:
1 | systemctl restart ssh |
即可。
十四、推荐最终配置
推荐:
1 | PermitRootLogin yes |
适合:
- 测试环境
- 开发服务器
- 临时运维
总结
Ubuntu 22 开启 root:
核心步骤:
| 步骤 | 内容 |
|---|---|
| 1 | passwd root |
| 2 | 开启 PermitRootLogin |
| 3 | 开启 PasswordAuthentication |
| 4 | 重启 SSH |
Ubuntu 22:
1 | 一定要注意 sshd_config.d |
否则:
1 | 配置可能不会生效 |
非常适合:
- Ubuntu 22
- 云服务器
- VPS
- Docker 主机
- Linux 运维