如何将 GitPython 与特定的 SSH 密钥一起使用?
该文档在该主题上不是很详尽。到目前为止,我唯一尝试过的是Repo(path)
.
以下在 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')
请注意,以下所有内容仅适用于 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()
...或更持久地使用存储库对象的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 中的新功能),您将在相应的问题中找到。
我在 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))
使用 repo.git.custom_environment 设置 GIT_SSH_COMMAND 不适用于 clone_from 函数。参考:https ://github.com/gitpython-developers/GitPython/issues/339
如果是clone_from
在 GitPython 中,Vijay 的答案不起作用。它在一个新实例中设置 git ssh 命令,Git()
然后实例化一个单独的Repo
调用。正如我从这里学到的那样,有效的方法是使用 的env
论点:clone_from
Repo.clone_from(url, repo_dir, env={"GIT_SSH_COMMAND": 'ssh -i /PATH/TO/KEY'})
我发现这让事情更像 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)
这反映了您的整个环境,更像是子外壳在 bash 中的工作方式。
无论哪种方式,将来创建 repo 或克隆的任何调用都会选择“调整后的”环境并执行标准的 git 身份验证。
不需要垫片脚本。
使用 Windows 时要小心放置引号的位置。说你有
git.Repo.clone_from(bb_url, working_dir, env={"GIT_SSH_COMMAND": git_ssh_cmd})
那么这个工作:
git_ssh_cmd = f'ssh -p 6022 -i "C:\Users\mwb\.ssh\id_rsa_mock"'
但这不会:
git_ssh_cmd = f'ssh -p 6022 -i C:\Users\mwb\.ssh\id_rsa_mock'
原因: