GitPython and SSH Keys?

Please note that all of the following will only work in GitPython v0.3.6 or newer.

You can use the GIT_SSH environment variable to provide an executable to git which will call ssh in its place. That way, you can use any kind of ssh key whenever git tries to connect.

This works either per call using a context manager ...

ssh_executable = os.path.join(rw_dir, 'my_ssh_executable.sh')
with repo.git.custom_environment(GIT_SSH=ssh_executable):
    repo.remotes.origin.fetch()

... or more persistently using the set_environment(...) method of the Git object of your repository:

old_env = repo.git.update_environment(GIT_SSH=ssh_executable)
# If needed, restore the old environment later
repo.git.update_environment(**old_env)

As you can set any amount of environment variables, you can use some to pass information along to your ssh-script to help it pick the desired ssh key for you.

More information about the becoming of this feature (new in GitPython v0.3.6) you will find in the respective issue.


I'm on GitPython==3.0.5 and the below worked for me.

from git import Repo
from git import Git    
git_ssh_identity_file = os.path.join(os.getcwd(),'ssh_key.key')
git_ssh_cmd = 'ssh -i %s' % git_ssh_identity_file
Repo.clone_from(repo_url, os.path.join(os.getcwd(), repo_name),env=dict(GIT_SSH_COMMAND=git_ssh_cmd))

Using repo.git.custom_environment to set the GIT_SSH_COMMAND won't work for the clone_from function. Reference: https://github.com/gitpython-developers/GitPython/issues/339


In case of a clone_from in GitPython, the answer by Vijay doesn't work. It sets the git ssh command in a new Git() instance but then instantiates a separate Repo call. What does work is using the env argument of clone_from, as I learned from here:

Repo.clone_from(url, repo_dir, env={"GIT_SSH_COMMAND": 'ssh -i /PATH/TO/KEY'})

Following worked for me on gitpython==2.1.1

import os
from git import Repo
from git import Git

git_ssh_identity_file = os.path.expanduser('~/.ssh/id_rsa')
git_ssh_cmd = 'ssh -i %s' % git_ssh_identity_file

with Git().custom_environment(GIT_SSH_COMMAND=git_ssh_cmd):
     Repo.clone_from('git@....', '/path', branch='my-branch')