Python 通过 SSH 身份验证克隆私有(private) GitHub 存储库,无需访问 ssh 二进制文件(在 Azure Functions 下)

标签 python azure paramiko gitpython dulwich

我们的团队需要在 Azure Function 中克隆一个私有(private) GitHub 存储库,您只能在其中运行 Python 代码 - 但无法访问 shell 或预安装的 Git 或 SSH 二进制文件。同时,我们无法对 GitHub 的 HTTPS API 使用 PAT token 身份验证 - 只允许 SSH 身份验证(基于 key )。

请注意,需要克隆存储库以获取其中的某些元数据和配置文件 - 而不是函数代码或 Python 包,因此,requirements.txt 不是我们要查找的内容。

如何做到这一点?

GitPython 包支持基于 SSH key 的身份验证,但依赖系统 SSH 二进制文件来实现这一点。我们还没有找到让它在 Azure Functions 环境下工作的方法。

P.S> 该问题与 self 回答一起发布(用于解决方案文档)。请参阅下面的答案。

最佳答案

我们发现以下两个项目都是纯Python的:

https://dulwich.io/ (Python Git 包) 和 https://www.paramiko.org/ (Python SSH包)

有证据表明它们可以一起工作(尽管作者表示他们认为这种支持是“实验性的”并且没有被测试覆盖),并且很难获得端到端的代码示例。

经过一些后端处理后,以下代码片段起作用了:

    from paramiko import  RSAKey
    import os
    import dulwich
    from dulwich import porcelain
    from dulwich.contrib.paramiko_vendor import ParamikoSSHVendor
    
    #Constants
    private_key_path = "~.ssh/id_rsa_githubrepo"
    repo_url = "<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="fc9b9588bc9b958894899ed29f9391" rel="noreferrer noopener nofollow">[email protected]</a>:myorg/myrepo.git"
    local_path = "/tmp/repo"
    
    # Load private key for SSH
    private_key = RSAKey(filename=private_key_path)
    ssh_kwargs = {"pkey": private_key}
    
    def get_dulwich_ssh_vendor():
        vendor = ParamikoSSHVendor(**ssh_kwargs)
        return vendor
    
    # overriding another module's method: gross! But there does not seem to be another way
    dulwich.client.get_ssh_vendor = get_dulwich_ssh_vendor

    # cloning
    repo = porcelain.clone(repo_url, target=local_path, checkout=True)

    #validation
    with open(os.path.join(local_path, "README.md"), "r") as f:
        print(f.read())
    ```

关于Python 通过 SSH 身份验证克隆私有(private) GitHub 存储库,无需访问 ssh 二进制文件(在 Azure Functions 下),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/77184704/

相关文章:

azure - 使用 AKS 上的 api 服务器地址访问集群应用程序

python - 添加 ssml 字符串后,我的 Azure 文本转语音应用程序不再输出

python - Ansible azure_rm_virtualmachine 在 Mac 上因缺少 pip 包而失败

python - 使用 Juniper 执行的 Paramiko 回显命令

python - Web2py 票证无效链接

python - 无极值的直方图均衡

python - 解析具有未定义实体的 XHTML5

即使 pip 说它已安装,Python 也无法导入 gdal - ubuntu hirsute & impish specific

python - Paramiko PKey.from_private_key_file 给我 "__init__() got an unexpected keyword argument ' 文件名'”

python - 在 Python Paramiko 中的 SSH 服务器上的辅助 shell/命令中执行(子)命令