python - GitPython - 使用 ssh key 克隆 - 主机 key 验证失败

标签 python git gitpython


我在我的应用程序中克隆 git 存储库时遇到问题。

KEY_FILE = "/opt/app/.ssh/id_rsa"

def read_git_branch(config_id, branch):
    config = RepoConfig.objects.get(id=config_id)
    save_rsa_key(Credentials.objects.get(id=1).key)
    git_ssh_identity_file = os.path.expanduser(KEY_FILE)
    git_ssh_cmd = 'ssh -i %s' % git_ssh_identity_file
    with Git().custom_environment(GIT_SSH_COMMAND=git_ssh_cmd):
        with tempfile.TemporaryDirectory() as tmpdir:
            repo = Repo.clone_from(config.url, tmpdir, branch=branch)
            branch_obj, _ = Branch.objects.get_or_create(name=branch)
            ....

def save_rsa_key(key):
    if not os.path.exists(os.path.dirname(KEY_FILE)):
        try:
            os.makedirs(os.path.dirname(KEY_FILE))
        except OSError as exc:
            if exc.errno != errno.EEXIST:
                raise
    with open(KEY_FILE, 'w') as id_rsa:
        id_rsa.write(key)
        os.chmod(KEY_FILE, 0o600)

预期结果是将存储库克隆到临时目录,对其进行处理并删除所有文件。
相反,我得到:

DEBUG/ForkPoolWorker-2] AutoInterrupt wait stderr: b'Host key verification failed.\nfatal: Could not read from remote repository.\n\nPlease make sure you have the correct access rights\nand the repository exists.\n'

git.exc.GitCommandError: Cmd('git') failed due to: exit code(128) cmdline: git clone --branch=master -v git@gitlab.foo:bar/project.git /tmp/tmpi_w2xhgt stderr: 'Host key verification failed.

当我尝试使用上面代码创建的 key 文件直接从机器连接到同一个存储库时:

ssh-agent bash -c 'ssh-add /opt/app/.ssh/id_rsa; git clone git@gitlab.foo:bar/project.git'

Repo 被毫无问题地克隆 + 主机被添加到 known_hosts。 完成后我的代码按预期工作...

它必须与 known_hosts 相关。有人遇到过类似的问题吗?

感谢您的帮助。

最佳答案

你应该使用 clone_from 的环境。

with Git().custom_environment(GIT_SSH_COMMAND=git_ssh_cmd):
    repo = Repo.clone_from(config.url, tmpdir, branch=branch)

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

关于python - GitPython - 使用 ssh key 克隆 - 主机 key 验证失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52592918/

相关文章:

python - 使用python从图像中提取补丁

python - 如何在 python 中关闭拉取请求?

python - 如何在 GitPython 中创建 Git 拉取请求

python - Scipy 中的高性能计算,具有独立应用于大量输入的数值函数

python - 安装了gst-python,但是找不到插件

git - 如何在 Visual Studio Code 中查看 Git 历史记录?

git - 显示与其他分支不同步的分支

VS 代码中的 Git 子模块意识不起作用

python - 如何使用 GitPython 获取提交中文件的源代码?

python - 如何强制 Python 在循环内创建新变量/新范围?