ozw*_*5rd 10 git authentication gitpython
我正在使用GitPython,但没有找到使用用户名和密码推送回购的方法.任何人都可以给我一个工作实例或给我一些关于如何做的指针吗?我需要做的是:将文件添加到存储库,使用提供的用户名和密码推送它.
什么对我有用(使用 GitHub,自托管 BitBucket,很可能也适用于 GitLab)。
请注意,尽管名称如此,但password这里是由 GitHub 生成的访问令牌,而不是您的 GitHub 密码。
from git import Repo
full_local_path = "/path/to/repo/"
username = "your-username"
password = "your-password"
remote = f"https://{username}:{password}@github.com/some-account/some-repo.git"
Run Code Online (Sandbox Code Playgroud)
这会将您的凭据存储在 中.git/config,以后您将不需要它们。
Repo.clone_from(remote, full_local_path)
Run Code Online (Sandbox Code Playgroud)
repo = Repo(full_local_path)
repo.git.add("rel/path/to/dir/with/changes/")
repo.index.commit("Some commit message")
Run Code Online (Sandbox Code Playgroud)
如上所述,您不需要您的凭据,因为它们已经存储在.git/config.
repo = Repo(full_local_path)
origin = repo.remote(name="origin")
origin.push()
Run Code Online (Sandbox Code Playgroud)
这是我自己用来拉的
#! /usr/bin/env python3
import git
import os
from getpass import getpass
project_dir = os.path.dirname(os.path.abspath(__file__))
os.environ['GIT_ASKPASS'] = os.path.join(project_dir, 'askpass.py')
os.environ['GIT_USERNAME'] = username
os.environ['GIT_PASSWORD'] = getpass()
g = git.cmd.Git('/path/to/some/local/repo')
g.pull()
Run Code Online (Sandbox Code Playgroud)
这与pull.py并且不仅限于 Github位于同一目录中。
#!/usr/bin/env python3
#
# Short & sweet script for use with git clone and fetch credentials.
# Requires GIT_USERNAME and GIT_PASSWORD environment variables,
# intended to be called by Git via GIT_ASKPASS.
#
from sys import argv
from os import environ
if 'username' in argv[1].lower():
print(environ['GIT_USERNAME'])
exit()
if 'password' in argv[1].lower():
print(environ['GIT_PASSWORD'])
exit()
exit(1)
Run Code Online (Sandbox Code Playgroud)
ozw*_*5rd -1
我找到了这个有效的解决方案:
Run Code Online (Sandbox Code Playgroud)os.environment['GIT_ASKPASS']= <full path to your script> os.environment['GIT_USERNAME'] = <committer username> os.environment['GIT_PASSWORD'] = <the password>
一切都很好。