289 字
1 分钟
macOS SSH 禁用密码认证仅允许密钥登录
1. SSH 服务开启
sudo systemsetup -getremotelogin # 显示 On/Offsudo systemsetup -setremotelogin on # 如未开启则打开
2. 「drop-in」方式配置
创建文件 /etc/ssh/sshd_config.d/010-keys-only.conf
(不存在则新建):
sudo sh -c 'cat >/etc/ssh/sshd_config.d/010-keys-only.conf << "EOF"# 仅允许公钥登录,彻底禁用口令/交互式/PAM 口令PubkeyAuthentication yesPasswordAuthentication noKbdInteractiveAuthentication noChallengeResponseAuthentication no
# 严格要求仅公钥通过(更保险)AuthenticationMethods publickey
# 一些常见的安全基线PermitEmptyPasswords noPermitRootLogin no# 可选:只允许特定用户/组# AllowUsers lkEOF'
说明:在 macOS 上,仅改
PasswordAuthentication no
仍可能通过 keyboard-interactive(PAM) 方式要密码;上面同时禁用KbdInteractiveAuthentication
并强制AuthenticationMethods publickey
,才能真正做到”密钥专用”。
3. 检查语法并重载
sudo /usr/sbin/sshd -t # 无输出即通过sudo launchctl kickstart -k system/com.openssh.sshd # 重新加载服务
4. 可选:只对部分用户强制密钥
如果你只想对某些用户强制密钥(其余仍允许密码),可以在上面的文件尾部加一个 Match 块:
Match User lk AuthenticationMethods publickey PasswordAuthentication no KbdInteractiveAuthentication no
建议:在远程环境操作时,保留一个已登录会话直到验证成功,避免因配置错误被锁在机器外。
macOS SSH 禁用密码认证仅允许密钥登录
https://blog.lpkt.cn/posts/macos-ssh-no-pwd-auth/