macOS 26 配置 SSH 密钥登录和修改 SSH 监听端口¶
致敬
谨以此文,致敬全世界修改SSH监听端口最麻烦的系统 —— macOS。
- 设备: Mac mini M4
- 系统: macOS 26.7.2
配置 SSH 密钥登录¶
-
在 Mac 上开启“远程登录”
系统设置 → 通用 → 共享 → 远程登录旁边的 ⓘ
开启“远程登录”,在“允许访问”中选择“仅这些用户”,添加你准备使用的账户。
“允许远程用户对磁盘进行完全访问”按实际文件访问需求决定。
-
在客户端生成 SSH 密钥: 参照创建和管理 Linux 服务器用于身份验证的 SSH 密钥
-
把公钥安装到 Mac
-
验证“只用密钥”可以登录
ssh -v \ -i ~/.ssh/your-private-key \ -o IdentitiesOnly=yes \ -o PreferredAuthentications=publickey \ -o PasswordAuthentication=no \ -o KbdInteractiveAuthentication=no \ -o ControlPath=none \ username@192.168.1.123成功时,调试信息中应出现类似信息:
-
在 Mac 上设置仅允许密钥登录
sudo tee /etc/ssh/sshd_config.d/00-user.conf >/dev/null <<'EOF' PubkeyAuthentication yes PasswordAuthentication no KbdInteractiveAuthentication no AuthenticationMethods publickey EOF sudo chown root:wheel /etc/ssh/sshd_config.d/00-user.conf sudo chmod 644 /etc/ssh/sshd_config.d/00-user.conf上述四项设置分别表示:
配置 作用 PubkeyAuthentication yes启用公钥认证 PasswordAuthentication no禁用密码认证 KbdInteractiveAuthentication no禁用键盘交互认证 AuthenticationMethods publickey明确要求通过公钥认证才能登录 -
检查语法和配置是否正确生效
检查配置语法:
正常情况下没有输出。有报错时,按提示修正。
查看配置是否正确生效:
sudo /usr/sbin/sshd -T | grep -E '^(PubkeyAuthentication|PasswordAuthentication|KbdInteractiveAuthentication|AuthenticationMethods)'预期结果如下:
-
验证密码无法登录 SSH
执行下面的反向测试:关闭客户端公钥认证,只尝试两种密码相关认证,并禁止连接复用。
ssh \ -o PubkeyAuthentication=no \ -o PreferredAuthentications=password,keyboard-interactive \ -o PasswordAuthentication=yes \ -o KbdInteractiveAuthentication=yes \ -o ControlPath=none \ username@192.168.1.123预期应被拒绝,例如:
修改 SSH 监听端口¶
-
修改
/etc/ssh/sshd_config.d/00-user.conf在
/etc/ssh/sshd_config.d/00-user.conf中,加入Port 2233 -
检查配置是否正确生效
预期输出:
-
创建服务配置
sudo tee /Library/LaunchDaemons/local.sshd-2233.plist >/dev/null <<'EOF' <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> <plist version="1.0"> <dict> <key>Label</key> <string>local.sshd-2233</string> <key>ProgramArguments</key> <array> <string>/usr/libexec/sshd-keygen-wrapper</string> </array> <key>Sockets</key> <dict> <key>Listeners</key> <dict> <key>SockServiceName</key> <string>2233</string> </dict> </dict> <key>inetdCompatibility</key> <dict> <key>Wait</key> <false/> </dict> </dict> </plist> EOF -
检查并加载服务
sudo chown root:wheel /Library/LaunchDaemons/local.sshd-2233.plist sudo chmod 644 /Library/LaunchDaemons/local.sshd-2233.plist plutil -lint /Library/LaunchDaemons/local.sshd-2233.plist sudo /usr/sbin/sshd -tplutil应显示 OK,sshd -t正常时没有输出。sudo launchctl enable system/local.sshd-2233 sudo launchctl bootstrap system /Library/LaunchDaemons/local.sshd-2233.plist然后检查服务状态和端口监听情况:
如果以后需要修改上述 plist,修改完成后记得重新加载服务:
-
停用默认 SSH 服务
再次检查端口监听情况:
注意
管理修改了 SSH 监听端口的自定义服务时,使用 launchctl 和上述自定义 plist。
系统设置中的“远程登录”开关管理的是默认 SSH 服务,无法控制修改了 SSH 监听端口的自定义服务。