32

I'm trying to connect to a Git repository (on Bitbucket) with SSH from Visual Studio 2017 (which, as far as I know, supports SSH for Git). I have everything set up, the repository cloned on my computer, and I can commit, but if I try to do something like fetching it fails with the following message (from Visual Studio's "Output" window):

Error encountered while fetching: Git failed with a fatal error.
fatal: Could not read from remote repository.

Trying it from the command prompt, I get these slightly more informative messages:

Permission denied (publickey).
fatal: Could not read from remote repository.

Please make sure you have the correct access rights
and the repository exists.

From Git Bash I have tried opening the SSH agent, adding my private key, and fetching, and it seems to work (or at least I don't get any messages, unlike when the agent is not started or the key not added):

eval `ssh-agent`
ssh-add ~/.ssh/xxxx
git fetch

But Visual Studio is still unable to connect. I have also tried to do the same from the Windows command prompt:

ssh-agent
set SSH_AUTH_SOCK=/tmp/ssh-SIAryCa61iz9/agent.11128
set SSH_AGENT_PID=9804
ssh-add xxxx
git fetch

But I still get the same error.

I already added the public key to Bitbucket, and ssh -T git@bitbucket.org does output "logged in as xxxx". Also, I can connect correctly using SourceTree and adding the private key to Pageant (the key I use for ssh-add has the required OpenSSH format, I created it from the .ppk one).

Trisibo
  • 1,085
  • 1
  • 10
  • 19
  • I'm using VS2017 Com. for Mac and having the same issues. Tried Mac-ish versions of the below, nothing. – Janet Jul 24 '18 at 22:19
  • Overall, connecting to Bitbucket by SSH is a bad idea, because there is no straightforward solution. Much easier way is to get Bitbucket tocken, store it in the Windows Credentials Manager, and use HTTPS link to access your repository. I could write a full blown answer if you are interested... – Sergey Nudnov Feb 01 '20 at 13:52

7 Answers7

43

I finally managed to make it work, using PuTTY's Pageant authentication agent instead of ssh-agent, and following the steps mentioned here (it's for Visual Studio Code, but works for Visual Studio 2017 and I guess it should work for any application that uses the "official" Git for Windows).

Since I already had Pageant installed and a .ppk private key created, I only had to make Git use Pageant, by creating the GIT_SSH Windows environment variable and setting it to the path of the "plink.exe" file (inside the PuTTY installation, for example C:\Program Files (x86)\PuTTY\plink.exe). With that done, I just need to open Pageant and add the private key (and leave it open while working with the repository), and Visual Studio will be able to connect and issue commands just fine.

Trisibo
  • 1,085
  • 1
  • 10
  • 19
  • to save pageant to keys permanently don't forget to add your ppk to shortcut target like: "C:\Program Files\PuTTY\pageant.exe" %userprofile%\.ssh\id_rsa.ppk – Ali Karaca Jan 20 '20 at 10:48
  • 1
    Also works for `C:\Program Files\TortoiseGit\bin\TortoiseGitPlink.exe` – Greg Domjan May 04 '20 at 06:17
  • 1
    Worked like a charm on VS2019...in my case I did not have a PuTTY separate install, and path to plink.exe was under SourceTree folder i.e. C:\Users\{user_name}\AppData\Local\SourceTree\app-3.3.8\tools\putty\, that came as a utility along with SourceTree.... – 1JD May 15 '20 at 21:07
  • 1
    If following that article and you're using an id_ed25519 key, that needs to be converted first to the .ppk file which you can use PuTTY for, but need to use version 0.71 or higher of puttygen.exe, otherwise it doesn't let you load the file to do the conversion. – Tahari Sep 06 '21 at 01:55
  • The solution in the mentioned link works like a charm with the exception that you should use the latest PuTTY installation, not only for the reason Tahari mentioned, but also because github removed weak cryptography standards. – Daniel Kaupp Apr 13 '22 at 09:19
  • I think they must have changed something in VS2022 to break this. It was working for me for a long time until I updated VS. I totally skips on authentication now despite having `GIT_SSH` set. – Jeff Mercado Jul 13 '22 at 20:13
13

there is another way, works for me.

  1. connect to Git repository use another ssh client, like ssh.exe. accept the connection. it will generate known_hosts file.
  2. copy known_hosts and id_rsa file into C:\Users\[UserName]\.ssh\
  3. Done. even without start-ssh-agent.

seems VS2017 run ssh connection on its own, so it ignores key that ssh-add added, and use default path's key only

Raven
  • 345
  • 2
  • 10
  • 1
    But does it really work for repositories that require an SSH key to connect? Placing id_rsa in C:\Users\[UserName]\.ssh\ doesn't work for me even if the key doesn't have a password, VS still can't connect unless I load the key into an authentication agent. – Trisibo Apr 21 '17 at 07:28
  • Yes, I create repository use "git init --bare" on the server, and access it through ssh://server-ip/some-path/repository.git. The ssh-key is used to login to that server. – Raven Apr 21 '17 at 09:03
  • And if you remove the id_rsa file it fails? – Trisibo Apr 21 '17 at 13:22
  • It will popup a window let me to enter passphrase if I removed id_rsa file. The passphrase is not for the key, but for the server. – Raven Apr 22 '17 at 01:03
  • 4
    This seems the easiest solution, I copied the files using Bash on Ubuntu on Windows: cp ~/.ssh/* /mnt/c/Users/[My User]/.ssh/ – Roland Oct 26 '17 at 10:38
  • 1
    This works great, many thanks! Although... VS then requires me to re-enter the passphrase for my id_rsa key file every single time I connect to Github. Not sure if the only way round this is to connect up to WSL's ssh-agent or PuTTY's plink, as per the other answers? – MikeBeaton Dec 20 '18 at 10:46
  • For me (using VS2019), I also had to copy the ~/.ssh/config file with "HostName" and "IdentityFile" specified. – Jess May 31 '21 at 16:06
7

Here is a solution which would allow to connect Visual Studio (and Git) to multiple repositories by SSH, with the separate private keys if necessary and ssh authentication agent to handle the keys' passphrases.

It is good for the corporate users, because you don't need administrator rights on your computer to follow the steps below.

It is explained on example of Bitbucket, but can be extended to Github and anything else.

Prerequisites

  • Installed Visual Studio
  • Bitbucket account

Download and install Git

On the opening of a project, Visual Studio will ask you to download and install Git package. You could do so using a link provided in a Visual Studio notification, or using this link.

Install Git for the current user only. Use installation options by default.

Generate your private/public keys pair

  1. Locate a Git folder with ssh-keygen.exe application. By default it is: "%LOCALAPPDATA%\Programs\Git\usr\bin\" for example: "C:\Users\NSM\AppData\Local\Programs\Git\usr\bin\"
  2. Open Command Prompt and go into the folder you found:

    cd "%LOCALAPPDATA%\Programs\Git\usr\bin\"
    
  3. Create a folder to store your keys if it doesn't exist

    mkdir "%HOME%\.ssh"
    
  4. Generate a new ssh key:

    ssh-keygen -t rsa -b 4096 -C "<your email of id>" -f "%HOME%/.ssh/id_rsa_<file name>"
    

    for example:

    ssh-keygen -t rsa -b 4096 -C "nsm" -f "%HOME%/.ssh/id_rsa_nsm"
    

    It is advisable to specify they key's passphrase. Remember the passphrase, you wont be able to recover it if forgotten!

Add your public key to Bitbucket

  1. Open your Bitbucket account management page
  2. Open the SSH keys section and click Add key
  3. Copy and paste content of the generated public key from the "%HOME%/.ssh/" folder. For example: id_rsa_nsm.pub: ssh-rsa AAAAB3Nza<skipped>BkPqxFQ== nsm
  4. Click Add key button to submit your public key

Configure ssh to use your key for Bitbucket source code requests

Create config file in the "%HOME%/.ssh/" folder with the following content:

    AddKeysToAgent yes

    Host <Bitbucket FQDN or any label>
      HostName <Bitbucket FQDN>
      User git
      IdentityFile ~/.ssh/id_rsa_<file name>

For example:

    cd %HOME%/.ssh/
    type config

Output:

    AddKeysToAgent yes

    Host bitbucket.org
      HostName bitbucket.org
      User git
      IdentityFile ~/.ssh/id_rsa_nsm

AddKeysToAgent yes option will add the configured private keys to the ssh authentication agent on demand

Configure Git to use ssh authentication agent

Typing the passphrase every time the private key has been used is a tedious burden. To avoid that we will use the ssh authentication agent

  1. In the folder, where the ssh-keygen utility was found (by default it is: "%LOCALAPPDATA%\Programs\Git\usr\bin\"), create ssh.cmd file with the following content:

    @echo off
    setlocal enabledelayedexpansion
    
    ::: File storing SSH_AUTH_SOCK and SSH_AGENT_PID of the running agent
    set __ssh_agent=%HOME%/.ssh/agent.env
    
    if exist %__ssh_agent% goto loadenv
    
    :startagent
    echo Starting SSH Authentication Agent...
    ssh-agent > %__ssh_agent%
    
    :loadenv
    ::: Loading the agent environment variables from 2 first lines of agent.env:
    ::: SSH_AUTH_SOCK and SSH_AGENT_PID
    set /a __count=0
    for /f "tokens=1 delims=;" %%a in (%__ssh_agent%) do (
      if !__count! LSS 2 (
        set %%a
        set /a __count+=1
      ) else (
        goto endloadenv
      )
    )
    :endloadenv
    
    ::: Checking the agent is running
    for /f "tokens=1 delims=, usebackq" %%a in (`TASKLIST /FI "PID eq %SSH_AGENT_PID%" /FO CSV /NH`) do (
      if not %%a == "ssh-agent.exe" goto startagent
    )
    
    :startssh
    ::: Run ssh, passing to it all command line parameters
    ssh.exe %*
    

    This script will load the ssh authentication agent before ssh.exe is executed and allow ssh.exe to communicate with it through socket specified in the SSH_AUTH_SOCK environment variable.

  2. From the Command Prompt execute the following command:

    git config --global core.sshCommand '%LOCALAPPDATA%/Programs/Git/usr/bin/ssh.cmd'
    

Create a remote for your local repository using the Bitbucket provided link

Replace FQDN in the link with a label you provided in the ./ssh/config file. That will allow you to use config sections with the multiple keys when connecting to Bitbucket or Github repositories

All Done

Sergey Nudnov
  • 1,327
  • 11
  • 20
  • 1
    This is the best solution when running with VS and the credential manager. Unlike the pageant solution you get prompted for passphrase if the key is not loaded into the agent, also by tweaking the cmd file you can also have the keys removed after a number of seconds. I ran into a few issues with these instruction but at the end of the day this was the solution I was looking for to get ssh agent working inside VS. First I already had the .ssh folder but %HOME% does not exist by default you need to use %HOMEPATH% or %USERPROFILE% or use the bash shell and use ~/ as needed i.e. mkdir ~/.ssh – Chris Jul 06 '19 at 22:11
  • Next putting commands in program file etc can be problematic in a corporate environment when all software has to be installed officially, if so you can put it in .ssh as a logical place to keep it. – Chris Jul 06 '19 at 22:11
  • I am getting an error when trying to clone the repo - %PROGRAMFILES'\(X86'\)%/Git/usr/bin/ssh.cmd: line 0: fg: no job control Do you know any reason why this is happening? – HashCoder Jan 31 '20 at 11:47
  • @HashCoder, I think you are trying to use this solution from Windows Subsystem for Linux, from a bash shell. Bash expects `ssh.cmd` to be a shell script, and fails to run it – Sergey Nudnov Feb 01 '20 at 13:47
  • @SergeyNudnov I tried to clone SSH URL using Visual Studio and mentioned path to ssh.cmd in the gitconfig file under core sshcommand – HashCoder Feb 03 '20 at 10:14
2

For me (Visual Studio 2019), it worked after adding a new system-wide environment variable GIT_SSH with the value C:\Program Files\TortoiseGit\bin\TortoiseGitPlink.exe (TortoiseGit's plink) TortoiseGitPlink.exe). Putty's plink.exe did not do the trick for me. Maybe because I am using TortoiseGit. After adding this, remember to restart Visual Studio.

daboss
  • 21
  • 3
1

Well, I couldn't find the direct way to configure Git repository with VS 2017 as the Clone option accepts only the URI not the SSH.

I did the following:

  1. Generated SSH key using Git Bash and synced the Git server with the keys generated by Git bash. You should be giving the public key under Settings.
  2. Downloaded Sourcetree client and configured it with SSH key Options->General->SSH Client Configuration -> Need to give the private key generated by Git bash
  3. Clone the client using Source tree and Open the same solution from Visual Studio. Push/Pull will work as usual.

Using Git Bash to generate the Keys you may find here.

Stephen Rauch
  • 47,830
  • 31
  • 106
  • 135
  • 1
    Cloning an SSH repo path worked for me in VS2017 15.9.2, so it looks like that's been fixed now. As an alternative to installing Git for Windows you can also use the [Windows Subsystem for Linux](https://learn.microsoft.com/en-us/windows/wsl/about) to generate keys etc, then set up .ssh/config in your home directory for the built-in VS ssh client (as in @Raven 's answer - just remember that VS looks in your Windows home directory, not the WSL one). – Simon Brady Nov 21 '18 at 00:08
  • There is a different URI for each repository to clone it using SSH - but it's still a URI. You can find both by clicking between "Use SSH" and "Use HTTPS" in Github's "Clone or download" pop-up. – MikeBeaton Dec 20 '18 at 10:57
0

This way worked for me (VS 2017 / Win7):

  1. I installed git-scm and connected with it.
  2. Done (nothing to copy, it just works)
ndberg
  • 3,391
  • 1
  • 21
  • 36
0

In VS2017

I had same problem.i tried a few method for solution :

  1. Removed "git for windows" on Visual Studio Installer and delete git on control panel
  2. Installed two of them.
  3. tried some ssh settings

but not solved my problem. And i opened "Visual Studio Installer" and repaired.it was solved.

ahmeticat
  • 1,899
  • 1
  • 13
  • 28