VS Code Remote-SSH 密钥免密登录配置 - VS Code 效率与避坑指南 01

问题概览卡片

基本信息

  • 问题分类:SSH 鉴权配置 / 开发流优化
  • 环境说明:任意支持 OpenSSH 的本地终端(如 Git Bash, macOS Terminal)及远程 Linux 服务器
  • 触发条件:新环境初始化、首次配置 VS Code 远程工作区。
  • 核心目标:建立非对称加密信任关系,实现 VS Code 丝滑直连。

现场执行日志(以 Git Bash 部署为例)

以下是使用 ssh-copy-id 命令将本地公钥推送至远程主机的标准中间过程证明(已脱敏):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
$ ssh-copy-id -i ~/.ssh/id_rsa.pub your_username@your_remote_host
/usr/bin/ssh-copy-id: INFO: Source of key(s) to be installed: "/c/Users/your_username/.ssh/id_rsa.pub"
The authenticity of host 'your_remote_host (10.x.x.x)' can't be established.
ED25519 key fingerprint is SHA256:abcdfssxxxxxxxxxxxxxxxxxAA.
This host key is known by the following other names/addresses:
~/.ssh/known_hosts:34: your_remote_host.domain.net
Are you sure you want to continue connecting (yes/no/[fingerprint])? yes
/usr/bin/ssh-copy-id: INFO: attempting to log in with the new key(s), to filter out any that are already installed
/usr/bin/ssh-copy-id: INFO: 1 key(s) remain to be installed -- if you are prompted now it is to install the new keys
your_username@your_remote_host's password:

Number of key(s) added: 1

Now try logging into the machine, with: "ssh 'your_username@your_remote_host'"
and check to make sure that only the key(s) you wanted were added.

1. 现象描述与痛点还原

VS Code 的 Remote 架构会在后台建立多个 SSH 连接(用于文件同步、终端进程、插件扩展等)。如果你只依赖传统的密码认证,由于 VS Code 本身并不缓存 SSH 密码,就会导致每一次新建底层连接时,顶部命令面板都会强制弹出密码输入框。不仅打断开发心流,一旦输错还需要重新走一遍加载流程。

2. 原理解析与根本原因

  1. 鉴权机制降级:SSH 协议优先尝试基于密钥(Key-based)的认证。当找不到有效私钥,或远程服务器没有录入对应的公钥时,系统就会降级到键盘交互式的密码认证(Password-based)。
  2. 首次连接的安全屏障:从上方日志可以看出,首次连接某台主机时,SSH 会触发 authenticity can't be established 的警告。这是防范中间人攻击的安全机制,必须手动输入 yes 将该主机的指纹记录到本地的 known_hosts 文件中,随后再输入密码,才能完成公钥的下发。

3. 标准化解决方案

步骤一:本地生成密钥对(若已有可跳过)

打开本地终端(Windows 用户请务必使用 Git Bash 或 PowerShell),执行生成命令:

1
2
3
4
# 推荐使用性能和安全性更佳的 ed25519 算法
ssh-keygen -t ed25519

# 交互提示中直接一路回车。请保持 passphrase 为空,否则后续仍需输入密钥保护密码。

步骤二:向远程服务器签发公钥

利用日志中展示的 ssh-copy-id 工具,将本地公钥安全地追加到服务器的授权列表中:

1
2
# 将下方的用户名和主机替换为你的实际信息
ssh-copy-id -i ~/.ssh/id_ed25519.pub your_username@your_remote_host

输入最后一次密码后,看到提示 Number of key(s) added: 1 即表示公钥已成功入驻远程服务器。

步骤三:修改 VS Code 的 SSH 配置文件

告知 VS Code 应该使用哪把“钥匙”去开门。

  1. 在 VS Code 按 Ctrl+Shift+P (Mac 为 Cmd+Shift+P)。
  2. 搜索并点击 Remote-SSH: Open SSH Configuration File...
  3. ~/.ssh/config 中为你配置的主机添加 IdentityFile 字段:
1
2
3
4
5
Host my-dev-server
HostName 10.x.x.x
User your_username
Port 22
IdentityFile ~/.ssh/id_ed25519

配置保存后,点击 VS Code 的连接按钮,即可全程无感直达远程工作区。


4. 常见排坑与预防建议

  • 严格的权限控制(最容易踩的坑)
    SSH 守护进程(sshd)对存放公钥的文件权限要求极其苛刻。如果服务器端的目录权限过大,出于安全考虑,免密登录会直接失效。请确保远程主机执行了以下授权:

    1
    2
    chmod 700 ~/.ssh
    chmod 600 ~/.ssh/authorized_keys
  • 配置覆盖问题
    如果你的电脑上配置了多个 Git 账号或多把私钥,一定要在 ~/.ssh/config 中通过不同的 Host 节点将 IdentityFile 隔离开来,避免密钥串联导致的认证失败。