GitPython和SSH密钥?

and*_*ari 12 python git ssh-keys gitpython

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

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

Vij*_*tam 10

以下是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')
Run Code Online (Sandbox Code Playgroud)


Byr*_*ron 8

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

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

这可以使用上下文管理器每次调用...

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

...或者更持久地使用存储库对象的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)
Run Code Online (Sandbox Code Playgroud)

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

有关此功能的更多信息(GitPython v0.3.6中的新功能),您将在相应的问题中找到.

  • 必须承认我也在为此苦苦挣扎。我真的不愿意编写自定义SSH脚本。有什么方法可以仅识别要使用的密钥?我对Python不熟悉,而tutorial / API并不能完全满足我的需要。谢谢。 (3认同)
  • 我不明白在这里做什么......我应该把我的 ssh 密钥的路径放在哪里? (3认同)

3lo*_*okh 7

我在 GitPython==3.0.5 上,以下对我有用。

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))
Run Code Online (Sandbox Code Playgroud)

使用 repo.git.custom_environment 设置 GIT_SSH_COMMAND 不适用于 clone_from 函数。参考:https : //github.com/gitpython-developers/GitPython/issues/339


sha*_*adi 5

clone_fromGitPython 的情况下,Vijay 的答案不起作用。它在一个新Git()实例中设置 git ssh 命令,然后实例化一个单独的Repo调用。正如我从这里学到envclone_from,使用 的参数是有效的:

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