GitPython and SSH keys?

How can I use GitPython with certain SSH keys?

The documentation is not very thorough on this. The only thing I've tried so far is Repo(path) .

+9
source share
3 answers

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

You can use the GIT_SSH environment variable to provide a git executable that will call ssh in its place. That way, every time git tries to connect, you can use any ssh key.

This works for every call with the 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 aggressively use the set_environment(...) method of your repository's Git object:

 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 number of environment variables, you can use some to transfer information to your ssh-script to help you choose the desired ssh key for you.

You can find more about how to become this function (new in GitPython v0.3.6) in the corresponding problem .

+7
source

The 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') 
+6
source

I found this a bit like the way git works in the shell.

 import os from git import Git, Repo global_git = Git() global_git.update_environment( **{ k: os.environ[k] for k in os.environ if k.startswith('SSH') } ) 

This is basically copying SSH environment variables to GitPython "shadow" environment. Then it uses the SSH-AGENT general authentication mechanisms, so you don’t have to worry about specifying exactly which key it is.

For a faster alternative that carries a lot of nonsense, but it works too:

 import os from git import Git global_git = Git() global_git.update_environment(**os.environ) 

This reflects your entire environment, more like a subshell in bash.

In any case, any future call to create a repo or clone takes away the "customized" environment and performs standard git authentication.

No scripts required.

0
source

Source: https://habr.com/ru/post/981904/


All Articles