在Windows上使用WSL2和VS代码容器进行SSH转发 [英] SSH forwarding using WSL2 and VS code containers on Windows

查看:18
本文介绍了在Windows上使用WSL2和VS代码容器进行SSH转发的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我让Ubuntu在Windows的WSL2下运行。在Ubuntu中,我克隆了我的存储库,该存储库设置为运行docker。当我在项目内部运行docker-compose up时,它成功启动,并且我可以从Windows上的VS代码打开容器。

当我试图从VS代码内部使用任何GIT功能时,就会出现这个问题。我只得到了一个permission denied (publickey)。如果我打开VS代码内部的终端(它连接到容器),则在运行git pull时得到相同的错误。

如果我在Ubuntu终端运行docker-compose run web bash,就可以成功运行git pull。因此,代理被转发到容器,它只是不能在VS代码中工作。

我是否遗漏了某些设置?

wsl2

要让VS代码在推荐答案后端上运行的Docker容器内使用您的wsl2实例中的ssh密钥,您需要告诉wsl2在启动时创建一个ssh代理,并将ssh密钥添加到该代理。当VS代码附加到在WSL2后端上运行的容器时,它将自动拾取正在运行的ssh代理,并允许您使用容器内的WSL2 SSH密钥进行身份验证。

对于任何一种方法,您都需要在WSL2中安装socat

sudo apt install socat

方法1-手动Bash脚本

要告诉您的WSL2发行版在引导时启动它的ssh-agent,您需要将以下行添加到您的~/.bash_profile或~/.zprofile(对于Zsh),以便在WSL2启动时启动ssh-agent:

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的末尾添加以下行,以便在使用bash时正确获取~/.bashrc

# 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

这篇关于在Windows上使用WSL2和VS代码容器进行SSH转发的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆