在今天的网络安全环境下,对root账户禁用密码登录并启用密钥认证,不是可选的"优化",而是必须的"基础安全措施"。这是保护服务器不被自动化攻击和暴力破解的第一道、也是最有效的防线。
在 CentOS 9 上关闭 root 密码登录并启用 SSH 密钥登录,请按照以下步骤操作:
1. 生成 SSH 密钥(在本地电脑上)
# 在本地机器生成密钥对 ssh-keygen -t rsa -b 4096 # 或使用 ed25519(更推荐) ssh-keygen -t ed25519
在本地用户目录下,如:c:\Users\AlbertWen\.ssh\
2. 将公钥上传到服务器
# 方法1:使用 ssh-copy-id(需要当前可以密码登录) ssh-copy-id root@服务器IP # 方法2:手动复制(推荐) # 将本地 ~/.ssh/id_rsa.pub 或 ~/.ssh/id_ed25519.pub 内容 # 复制到服务器的 ~/.ssh/authorized_keys 文件中
3. 配置 SSH 服务器
编辑 SSH 配置文件:
vi /etc/ssh/sshd_config
修改以下参数:
# 禁用密码认证 PasswordAuthentication no # 禁用 root 密码登录(但允许密钥登录) PermitRootLogin prohibit-password # 或者更严格,只允许密钥登录: # PermitRootLogin without-password # 启用公钥认证 PubkeyAuthentication yes # 可选:禁用空密码 PermitEmptyPasswords no # 可选:更改 SSH 端口(提高安全性) # Port 2222 # 确保以下参数已启用(通常默认是) AuthorizedKeysFile .ssh/authorized_keys
4. 确保权限正确
# 设置正确的目录和文件权限 chmod 700 ~/.ssh chmod 600 ~/.ssh/authorized_keys chown -R root:root ~/.ssh # 检查 SELinux 上下文(如果启用) restorecon -R -v ~/.ssh
5. 测试配置并重启服务
# 测试配置文件语法 sshd -t # 重启 SSH 服务 systemctl restart sshd # 设置服务开机自启 systemctl enable sshd
6. 重要:测试连接
在关闭当前 SSH 会话前,新开一个终端测试连接:
ssh -i ~/.ssh/私钥文件 root@服务器IP
7. 防火墙配置(如果更改了 SSH 端口)
# 查看防火墙状态 systemctl status firewalld # 如果更改了 SSH 端口,添加新端口 firewall-cmd --permanent --add-port=2222/tcp firewall-cmd --reload # 或移除默认端口(谨慎操作) firewall-cmd --permanent --remove-service=ssh firewall-cmd --reload
注意事项:
1. 备份原始配置文件:
cp /etc/ssh/sshd_config /etc/ssh/sshd_config.bak
2. 保留至少一个具有 sudo 权限的非 root 用户作为备用:
# 创建新用户 adduser yourusername # 设置密码 passwd yourusername # 添加到 wheel 组(有 sudo 权限) usermod -aG wheel yourusername
3. 如果密钥登录失败,可以通过控制台或救援模式恢复访问。
4. 考虑使用 Fail2Ban 增强安全性:
dnf install epel-release dnf install fail2ban systemctl enable --now fail2ban
完成这些步骤后,root 账户将只能使用 SSH 密钥登录,大大提高了系统的安全性。