如何限制SSH登录:仅允许通过.pem密钥文件登录,禁止无密钥访问
解决SSH必须使用指定.pem密钥登录的问题
1. 检查并加固sshd服务配置
编辑SSH服务端配置文件(通常路径为/etc/ssh/sshd_config),确保以下配置项设置正确:
- 彻底禁用密码及挑战响应式认证:
PasswordAuthentication no ChallengeResponseAuthentication no - 强制仅允许公钥认证:
PubkeyAuthentication yes AuthenticationMethods publickey - 可选:限制仅指定用户可通过SSH登录(进一步缩小访问范围):
AllowUsers your_target_username
修改完成后,务必重启sshd服务使配置生效:
- Debian/Ubuntu系统:
sudo systemctl restart sshd - RHEL/CentOS系统:
sudo systemctl restart sshd - 老旧系统:
sudo service ssh restart
2. 清理服务器端授权密钥
你能直接用ssh user@host登录,本质是本地SSH客户端自动加载了其他已授权的密钥(比如~/.ssh/id_rsa这类默认密钥),且这些密钥的公钥已存在于服务器端用户目录的~/.ssh/authorized_keys文件中。
解决方法:
- 登录服务器,打开
~/.ssh/authorized_keys文件,仅保留你的.pem密钥对应的公钥条目,删除所有其他无关的公钥内容 - 确保
~/.ssh目录权限为700,authorized_keys文件权限为600,避免权限过宽导致的认证问题:chmod 700 ~/.ssh chmod 600 ~/.ssh/authorized_keys
3. 验证效果
完成上述操作后,在本地尝试:
- 直接执行
ssh user@host:此时因无匹配的授权密钥,会返回权限拒绝,无法登录 - 执行指定密钥的命令
ssh -i /path/to/your.pem user@host:可正常登录
若客户端需要更便捷的指定密钥方式,可编辑本地~/.ssh/config文件,添加该主机的专属配置:
Host your_host_alias HostName your_host_ip_or_domain User your_username IdentityFile /path/to/your.pem
之后只需执行ssh your_host_alias即可自动使用指定密钥登录,同时避免了无密钥登录的可能。
内容的提问来源于stack exchange,提问作者Shanthini M
相关产品推荐
相关产品推荐

