GitPython和SSH密钥?

问题描述 投票:9回答:3

如何使用GitPython和特定的SSH密钥?

关于该主题的文档不是很全面。到目前为止我唯一尝试过的是Repo(path)

python git ssh-keys gitpython
3个回答
7
投票

请注意,以下所有内容仅适用于GitPython v0.3.6或更高版本。

您可以使用GIT_SSH环境变量为git提供可执行文件,它将在其位置调用ssh。这样,每当git尝试连接时,您都可以使用任何类型的ssh密钥。

这可以使用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()

...或者更持久地使用存储库的set_environment(...)对象的Git方法:

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

由于您可以设置任意数量的环境变量,您可以使用一些来将信息传递给您的ssh脚本,以帮助它为您选择所需的ssh密钥。

有关此功能的更多信息(GitPython v0.3.6中的新功能),您将找到in the respective issue


7
投票

以下是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')

1
投票

我发现这使得事情更像是git在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') }
)

它主要是将SSH环境变量复制到GitPython的“阴影”环境中。然后,它使用常见的SSH-AGENT身份验证机制,因此您不必担心确切地指定它是哪个密钥。

对于一个更快的替代方案,它可能带有很多瑕疵,但它也有效:

import os
from git import Git

global_git = Git()
global_git.update_environment(**os.environ)

这反映了整个环境,更像是子shell在bash中的工作方式。

无论哪种方式,任何未来创建回购或克隆的调用都会选择“已调整”的环境并执行标准的git身份验证。

不需要垫片脚本。

© www.soinside.com 2019 - 2024. All rights reserved.