Windows → Ubuntu 服务器 SSH 免密码登录配置(VSCode适用)

VSCode(终端连接同样适用)通过SSH远程连接服务器通常要输入2-4次密码,非常繁琐(熟练的让人心疼)。为了解决这一问题,这篇记录一下如何在 Windows 上生成 SSH 密钥,并配置 Ubuntu 服务器免密码登录。配置完成后,可以直接通过 PowerShell 或 VSCode Remote SSH 连接服务器。

1. 在 Windows 生成 SSH 密钥

打开 Windows PowerShell,执行:

powershell 复制代码
ssh-keygen -t ed25519

一路回车即可,默认会生成在当前用户目录下:

text 复制代码
C:\Users\你的用户名\.ssh\id_ed25519
C:\Users\你的用户名\.ssh\id_ed25519.pub

其中:

  • id_ed25519 是私钥,保存在本地,不要泄露;

  • id_ed25519.pub 是公钥,需要添加到服务器。

这里使用 ed25519,相比传统的 rsa,它更安全,生成速度也更快。

2. 将公钥添加到服务器

先在 Windows 中打开公钥文件:

powershell 复制代码
notepad "$env:USERPROFILE\.ssh\id_ed25519.pub"

复制文件中的全部内容。

然后通过密码登录一次服务器:

powershell 复制代码
ssh ubuntu@192.168.XX.XX

登录后,在服务器上创建 SSH 配置目录,并编辑 authorized_keys 文件:

bash 复制代码
mkdir -p ~/.ssh
nano ~/.ssh/authorized_keys

将刚才复制的公钥粘贴进去。注意一个公钥占一行。

保存后,设置权限:

bash 复制代码
chmod 700 ~/.ssh
chmod 600 ~/.ssh/authorized_keys

这一步很重要。如果权限过宽,SSH 可能会拒绝使用公钥认证。

3. 测试免密码登录

退出服务器:

bash 复制代码
exit

然后在 Windows PowerShell 中重新连接:

powershell 复制代码
ssh ubuntu@192.168.XX.XX

如果不再要求输入密码,说明 SSH 免密码登录已经配置成功。

4. 配置 VSCode Remote SSH 快捷连接

为了方便在 VSCode 中连接,可以编辑 Windows 本地的 SSH 配置文件:

powershell 复制代码
notepad "$env:USERPROFILE\.ssh\config"

加入以下内容:

text 复制代码
Host dell7920
    HostName 192.168.XX.XX
    User ubuntu
    IdentityFile ~/.ssh/id_ed25519
    IdentitiesOnly yes

保存后,在 VSCode 的 Remote SSH 中选择 dell7920,即可直接连接服务器。

5. 配置完成后的结构

text 复制代码
Windows / VSCode
        |
        |  SSH Key
        v
Ubuntu Server

愉快的调试吧!