要让 VS Code 在 WSL2 后端上运行的 Docker 容器内使用 WSL2 实例中的 SSH 密钥,您需要告诉 WSL2 在启动时创建一个 ssh-agent 和 将您的 ssh 密钥添加到代理。当 VS Code 附加到在 WSL2 后端运行的容器时,它会自动获取正在运行的 ssh-agent,并允许您使用容器内的 WSL2 SSH 密钥进行身份验证。
对于任何一种方法,您都需要在 WSL2 中安装 socat
sudo apt install socat
方法 1 - 手动 Bash 脚本
要告诉您的 WSL2 发行版在启动时启动它的 ssh-agent,您需要将这些行添加到您的 ~/.bash_profile 或 ~/.zprofile(对于 Zsh),以便 ssh-agent 在 WSL2 启动时启动:
if [ -z "$SSH_AUTH_SOCK" ]; then
# Check for a currently running instance of the agent
RUNNING_AGENT="`ps -ax | grep 'ssh-agent -s' | grep -v grep | wc -l | tr -d '[:space:]'`"
if [ "$RUNNING_AGENT" = "0" ]; then
# Launch a new instance of the agent
ssh-agent -s &> $HOME/.ssh/ssh-agent
fi
eval `cat $HOME/.ssh/ssh-agent`
fi
# also add your key to this ssh-agent session
#
# When run without arguments, it adds the files ~/.ssh/id_rsa, ~/.ssh/id_dsa,
# ~/.ssh/id_ecdsa, ~/.ssh/id_ecdsa_sk, ~/.ssh/id_ed25519, and ~/.ssh/id_ed25519_sk.
# Source: https://man.cx/ssh-add
ssh-add
# if you had to create ~/.bash_profile, these lines may also be needed
# to load your ~/.bashrc config
#
# test and run the .bashrc file if it exists (this is the default on Ubuntu for WSL2)
if [ -n "$BASH_VERSION" ]; then
# include .bashrc if it exists
if [ -f "$HOME/.bashrc" ]; then
. "$HOME/.bashrc"
fi
fi
方法 2 - 钥匙串
Keychain 基本上与上述相同,但使用一个简单的命令。默认情况下不会安装它,因此您必须使用发行版的包管理器或从源代码安装它。
sudo apt install keychain
安装钥匙串后,将以下内容添加到您的~/.bash_profile 或~/.zprofile:
# keychain will start the ssh agent and add the keys, or reuse the ssh agent
# if it is already running
eval `keychain --eval --agents ssh id_rsa`
# ...
您还可以使用钥匙串来设置您的 GPG 密钥(如果有)。
如果~/.bash profile 尚不存在,(它不适用于在 WSL2 上默认安装的 Ubuntu),那么您需要将以下行添加到您的 ~/.bash_profile 的末尾,以便 ~/.bashrc 是使用 bash 时来源正确。
# run the .bashrc file if it exists (this is the default on WSL2 if this does not already exist)
# these lines may already exist if .bash_profile already exists
if [ -n "$BASH_VERSION" ]; then
# include .bashrc if it exists
if [ -f "$HOME/.bashrc" ]; then
. "$HOME/.bashrc"
fi
fi
参考文献
https://code.visualstudio.com/docs/remote/containers#_using-ssh-keys
https://github.com/microsoft/vscode-remote-release/issues/2925#issuecomment-652558889