289 字
1 分钟
macOS SSH 禁用密码认证仅允许密钥登录
2025-08-20

1. SSH 服务开启#

Terminal window
sudo systemsetup -getremotelogin # 显示 On/Off
sudo systemsetup -setremotelogin on # 如未开启则打开

2. 「drop-in」方式配置#

创建文件 /etc/ssh/sshd_config.d/010-keys-only.conf(不存在则新建):

Terminal window
sudo sh -c 'cat >/etc/ssh/sshd_config.d/010-keys-only.conf << "EOF"
# 仅允许公钥登录,彻底禁用口令/交互式/PAM 口令
PubkeyAuthentication yes
PasswordAuthentication no
KbdInteractiveAuthentication no
ChallengeResponseAuthentication no
# 严格要求仅公钥通过(更保险)
AuthenticationMethods publickey
# 一些常见的安全基线
PermitEmptyPasswords no
PermitRootLogin no
# 可选:只允许特定用户/组
# AllowUsers lk
EOF'

说明:在 macOS 上,仅改 PasswordAuthentication no 仍可能通过 keyboard-interactive(PAM) 方式要密码;上面同时禁用 KbdInteractiveAuthentication 并强制 AuthenticationMethods publickey,才能真正做到”密钥专用”。

3. 检查语法并重载#

Terminal window
sudo /usr/sbin/sshd -t # 无输出即通过
sudo launchctl kickstart -k system/com.openssh.sshd # 重新加载服务

4. 可选:只对部分用户强制密钥#

如果你只想对某些用户强制密钥(其余仍允许密码),可以在上面的文件尾部加一个 Match 块:

Terminal window
Match User lk
AuthenticationMethods publickey
PasswordAuthentication no
KbdInteractiveAuthentication no

建议:在远程环境操作时,保留一个已登录会话直到验证成功,避免因配置错误被锁在机器外。

macOS SSH 禁用密码认证仅允许密钥登录
https://blog.lpkt.cn/posts/macos-ssh-no-pwd-auth/
作者
lollipopkit
发布于
2025-08-20
许可协议
CC BY-NC-SA 4.0