重定向'git clone'的stdout/stderr/stdin
我想写一个程序,它可以克隆远程的git仓库,然后再做一些其他的事情。问题是,'git clone'会要求输入密码。当我尝试通过管道将输入/输出/错误传给'git clone'时,它实际上在后台运行git-remote-http,而这个程序会在终端上提示输入密码。
我想从我的程序里传递密码。我正在使用Python和subprocess中的Popen。下面的代码不起作用。
Popen(['git', 'clone', 'https://my.git.repo/repo.git'], shell=False, stdin=PIPE, stdout=PIPE, stderr=PIPE)
我该怎么做才能实现这个呢?
3 个回答
1
如果你愿意使用一个库的话,可以试试 Dulwich。
from dulwich import porcelain
porcelain.clone("https://example.com/repo.git", username="youruser", password="yourpassword")
看起来这个库并不存储用户名或密码(我在 .git
目录里找过用到的密码,但没有找到任何东西)。
来源
因为找到一个没有明显问题的最新 Git 库实在不容易,所以我想列出我的一些来源,方便以后参考:
- PTBNL 在 2009 年回答的“Python Git 模块经验?[已关闭]”,推荐了(其中包括)使用 Dulwich。
- Trishayyyy 在 2019 年回答的“在 Python 代码中使用 Git 命令”,仍然推荐使用 Dulwich(和 PyGit)。
- Dulwich
porcelain
文档,关于clone
的内容,但可惜没有提到可以进行身份验证。 - harvin 的回答“dulwich - 从远程仓库克隆时的身份验证”,提到使用 Dulwich
clone
确实可以进行身份验证,使用username:password@
的格式。 - 受到最后一个链接回答的启发,我进一步检查了源代码,发现了
username
和password
参数。我在我的回答中记录了这个,关于“dulwich - 从远程仓库克隆时的身份验证”问题。
2
你可以用 git clone https://foo:bar@my.git.repo/repo.git
这个命令来获取数据,之后再用 git remote set-url origin https://my.git.repo/repo.git
来清除密码。不过在你开始克隆和更改网址之间,有可能会出现一个竞争条件。
2
如果你不想像评论者说的那样使用挑战认证,我建议你可以使用 pexpect 来自动化这种交互。