在 CentOS 上遇到 SSH 权限错误(如 Permission denied (publickey)、Authentication refused: bad ownership or modes 等),通常是 文件权限 / 所有者 / SELinux / 配置 问题。下面按常见原因逐步排查。
~/.ssh 权限登录服务器后执行:
chmod 700 ~/.ssh
chmod 600 ~/.ssh/authorized_keys
chown -R $USER:$USER ~/.ssh
✅ 正确权限示例:
drwx------ .ssh
-rw------- authorized_keys
chmod 600 ~/.ssh/id_rsa
chmod 644 ~/.ssh/id_rsa.pub
编辑配置文件:
sudo vi /etc/ssh/sshd_config
确认以下项:
PubkeyAuthentication yes
AuthorizedKeysFile .ssh/authorized_keys
PasswordAuthentication yes # 排错时可临时开
修改后重启:
sudo systemctl restart sshd
SSH 对家目录要求严格:
chmod 755 ~
❌ 不能是 777
查看是否被 SELinux 拦截:
sudo tail -f /var/log/audit/audit.log
修复上下文:
restorecon -Rv ~/.ssh
临时测试(不推荐长期使用):
sudo setenforce 0
ssh -v user@ip
或
ssh -vvv user@ip
sudo tail -f /var/log/secure
| 错误信息 | 原因 |
|---|---|
| Permission denied (publickey) | 公钥未生效 / 权限错 |
| bad ownership or modes | .ssh 权限不对 |
| Connection closed by remote | SELinux / 配置错 |
| Too many authentication failures | 私钥太多 |
chmod 700 ~/.ssh
chmod 600 ~/.ssh/authorized_keys
chown -R $USER:$USER ~/.ssh
restorecon -Rv ~/.ssh
sudo systemctl restart sshd
如果你能贴出 具体错误信息(客户端或服务端日志),我可以直接帮你精确定位 ✅