Skip to content

SSH 免密(踩坑与解决)

目标:本机一条 ssh jy-test 就能登录,Cursor Agent 才能在后台替你执行命令。

测试机 SSH:root@154.89.148.95,端口 3337(不是 22)。

1. 本机别名

~/.ssh/config

ssh-config
Host jy-test
  HostName 154.89.148.95
  Port 3337
  User root
  IdentityFile ~/.ssh/id_ed25519_jy_test
  IdentitiesOnly yes

只加这段还不够,必须让服务器收下对应公钥,并且本机私钥没有密码

2. 第一次失败:服务器没开公钥

当时服务器 sshd 只提供:

text
gssapi-keyex,gssapi-with-mic,password

没有 publickey。需要在服务器打开:

text
PubkeyAuthentication yes

然后 systemctl reload sshd(或 service sshd reload)。

打开之后,认证方式会变成:

text
publickey,gssapi-keyex,gssapi-with-mic,password

3. 第二次失败:本机 RSA 有密码

公钥已经在 authorized_keys 里,日志甚至出现:

text
Server accepts key: ~/.ssh/id_rsa
Permission denied (publickey,...)

原因:id_rsa 有 passphrase。Cursor 的非交互终端不能输入密码,签名失败。ssh-agent 当时也是空的。

ssh -o BatchMode=yes 复现的就是这个问题。

4. 最终做法:单独一把无密码 ed25519

不要解锁个人 id_rsa 给 Agent 用。给这台测试机单独做一把无密码密钥:

bash
ssh-keygen -t ed25519 -f ~/.ssh/id_ed25519_jy_test -N "" -C "jy-test-cursor"

用密码登录把公钥追加到服务器(强制走密码,避免先试失败的密钥):

bash
cat ~/.ssh/id_ed25519_jy_test.pub | ssh -p 3337 \
  -o PreferredAuthentications=password \
  -o PubkeyAuthentication=no \
  root@154.89.148.95 \
  'mkdir -p ~/.ssh && chmod 700 ~/.ssh && cat >> ~/.ssh/authorized_keys && chmod 600 ~/.ssh/authorized_keys && echo INSTALLED'

Host jy-testIdentityFile 改成这把新密钥。验证:

bash
ssh -o BatchMode=yes jy-test 'hostname && whoami'

打印出主机名和 root 即成功。

5. 可忽略的警告

text
WARNING: connection is not using a post-quantum key exchange algorithm

服务器是 OpenSSH 7.4,算法偏旧。不是连不上的原因。

6. 不要做的事

  • 不要把 SSH 密码写进仓库、.env 或聊天记录长期保存
  • 不要用 sshpass 把密码写进脚本
  • 不要把个人有密码的 id_rsa 当成 Agent 的默认密钥
  • Host * 那一段如果被写成一行(Host *AddKeysToAgent yes...),macOS Keychain 不会生效

JY 项目文档