gitpython git authentication using user and password gitpython git authentication using user and password git git

gitpython git authentication using user and password


What worked well for me (worked with GitHub, self hosted BitBucket, most likely will work on GitLab too).

Pre-requisites

Note, that despite the name, password here is your access token generated by GitHub and NOT your GitHub password.

from git import Repofull_local_path = "/path/to/repo/"username = "your-username"password = "your-password"remote = f"https://{username}:{password}@github.com/some-account/some-repo.git"

Clone repository

This will store your credentials in .git/config, you won't need them later.

Repo.clone_from(remote, full_local_path)

Commit changes

repo = Repo(full_local_path)repo.git.add("rel/path/to/dir/with/changes/")repo.index.commit("Some commit message")

Push changes

As mentioned above, you don't need your credentials, since they are already stored in .git/config.

repo = Repo(full_local_path)origin = repo.remote(name="origin")origin.push()


This is what I used for myself for pulling

pull.py

#! /usr/bin/env python3import gitimport osfrom getpass import getpassproject_dir = os.path.dirname(os.path.abspath(__file__))os.environ['GIT_ASKPASS'] = os.path.join(project_dir, 'askpass.py')os.environ['GIT_USERNAME'] = usernameos.environ['GIT_PASSWORD'] = getpass()g = git.cmd.Git('/path/to/some/local/repo')g.pull()

askpass.py (similar to this one)

This is in the same directory as pull.py and is not limited to Github only.

#!/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 argvfrom os import environif 'username' in argv[1].lower():    print(environ['GIT_USERNAME'])    exit()if 'password' in argv[1].lower():    print(environ['GIT_PASSWORD'])    exit()exit(1)


I found this working solution:

  1. create a script like this: ask_pass.py
  2. before to execute push assign the environment vars:
   os.environment['GIT_ASKPASS']= <full path to your script>   os.environment['GIT_USERNAME'] = <committer username>   os.environment['GIT_PASSWORD'] = <the password>

and anything works fine.