DEV Community

loading...

How to Setup SSH Authentication for Git Bash on Windows

bsara profile image Brandon Sarà Updated on ・2 min read

I originally created this as a Gist on GitHub to be shared with some co-workers who were struggling to set up SSH on Windows. It seems to have been helpful to a lot of others as well; so, I'm posting it here so that it can benefit even more people.

Preparation

  1. Create a folder at the root of your user home folder (Example: C:/Users/uname/) called .ssh.
  2. Create the following files if they do not already exist (paths begin from the root of your user home folder):
    • .ssh/config
    • .bash_profile
    • .bashrc

Create a New SSH Key

Follow the steps in the section named "Generating a new SSH Key" found in the following documentation from GitHub:
Generating a new SSH key and adding it to the ssh-agent

Configure SSH for Git Hosting Server

Add the following text to .ssh/config (.ssh should be found in the root of your user home folder):

Host github.com
 Hostname github.com
 IdentityFile ~/.ssh/id_rsa
Enter fullscreen mode Exit fullscreen mode

Enable SSH Agent Startup Whenever Git Bash is Started

First, ensure that following lines are added to .bash_profile, which should be found in your root user home folder:

test -f ~/.profile && . ~/.profile
test -f ~/.bashrc && . ~/.bashrc
Enter fullscreen mode Exit fullscreen mode

Now, add the following text to .bashrc, which should be found in your root user home folder:

# Start SSH Agent
#----------------------------

SSH_ENV="$HOME/.ssh/environment"

function run_ssh_env {
  . "${SSH_ENV}" > /dev/null
}

function start_ssh_agent {
  echo "Initializing new SSH agent..."
  ssh-agent | sed 's/^echo/#echo/' > "${SSH_ENV}"
  echo "succeeded"
  chmod 600 "${SSH_ENV}"

  run_ssh_env;

  ssh-add ~/.ssh/id_rsa;
}

if [ -f "${SSH_ENV}" ]; then
  run_ssh_env;
  ps -ef | grep ${SSH_AGENT_PID} | grep ssh-agent$ > /dev/null || {
    start_ssh_agent;
  }
else
  start_ssh_agent;
fi
Enter fullscreen mode Exit fullscreen mode

You're Done!

Please, feel free to ask any questions that you may have in the comments, I’m more than happy to help.

Discussion (3)

pic
Editor guide
Collapse
formulatededits profile image
Formulated Paul

Hi,

Is the final step still required? I'm running Git for Windows and SSH seems to work fine without setting the agent to start. Unless I set it in the past and have forgotten...

Collapse
bsara profile image
Brandon Sarà Author

If it's working then you should be good. It's been quite a while since I've actually used windows for anything and given their efforts to integrate Linux features into the OS, it is possible that it is no longer necessary.

Collapse
formulatededits profile image
Formulated Paul

Thank you!