Ubuntu 虚拟机 SSH 连接笔记
一份可直接复制的小抄:从生成密钥、配置到 VS Code 连接与排错。
1. 生成/复用 SSH 密钥(Windows)
# 若已有 GitHub 密钥可直接复用;否则执行以下命令
ssh-keygen -t ed25519 -C "你的邮箱"
默认路径:
- 私钥:
C:\Users\<你的用户名>\.ssh\id_ed25519 - 公钥:
C:\Users\<你的用户名>\.ssh\id_ed25519.pub
✅ 已有 GitHub 密钥时,无需再生成,直接复用同一把 Key。
2. 将公钥放到 Ubuntu
mkdir -p ~/.ssh
nano ~/.ssh/authorized_keys
将 Windows 公钥 (id_ed25519.pub) 粘贴进去,保存退出,然后设置权限:
chmod 700 ~/.ssh
chmod 600 ~/.ssh/authorized_keys
3. Windows SSH 配置文件
路径:
C:\Users\<你的用户名>\.ssh\config
示例内容(注意缩进用空格,不要 Tab):
Host ubuntu-vm
HostName 192.168.217.128
User ubuntu
Port 22
IdentityFile C:\Users\<你的用户名>\.ssh\id_ed25519
4. 测试连接
ssh ubuntu-vm
ssh -v ubuntu-vm # 调试模式
关键输出:
Authentication succeeded (publickey).
出现这行就代表免密登录成功。
5. VS Code 远程开发(Remote - SSH)
- 安装扩展:Remote - SSH
- 左下角绿色按钮 → Connect to Host →
ubuntu-vm - 打开终端:Ctrl + `(反引号,数字 1 左边的键)
6. 常见易错点(速查)
- Windows SSH 配置:
C:\Users\<用户名>\.ssh\config - Ubuntu 公钥位置:
~/.ssh/authorized_keys - 缩进必须用空格,不能 Tab
- 权限:
chmod 700 ~/.ssh chmod 600 ~/.ssh/authorized_keys - IP 在 NAT 下通常固定,但可能变 → 可设置静态 IP
7. 常用检查命令
ip addr # 查看 Ubuntu 当前 IP
systemctl status ssh # SSH 服务状态
sudo apt update
sudo apt install -y openssh-server
sudo systemctl enable --now ssh # 若未安装 / 未启动
8. 记忆口诀
生成密钥 → 公钥进 Ubuntu → Windows 写 config
→ ssh 别名直连 → VS Code Remote-SSH