Search code examples
pythongitgithubsshgitpython

Git pull using GitPython + SSH keys doesn't work


I am trying to pull a repo from my Github account using GitPython. This is after

(1) I performed a git clone already from the command line.

(2) Generated new SSH keys using

ssh-keygen -t rsa -b 4096

(3) Setup the contents of the .pub file from #2 above in Github as a new SSH key.

I still get prompted to enter my Github username and password. Why is that ?

Here is the config in my .git folder. Note the http:// in the url instead of https://

[core]
    repositoryformatversion = 0
    filemode = true
    bare = false
    logallrefupdates = true
[remote "origin"]
    url = http://github.com/githubuser/myrepo.git
    fetch = +refs/heads/*:refs/remotes/origin/*
[branch "master"]
    remote = origin
    merge = refs/heads/master

Here is my code snippet

import git, os

DIR_NAME = 'path/to/dir/with/gitfolder'
git_ssh_identity_file = os.path.expanduser('/path/to/rsa/key')
git_ssh_cmd = 'ssh -i %s' % git_ssh_identity_file

with git.Git().custom_environment(GIT_SSH_COMMAND=git_ssh_cmd):

    repo = git.Repo.init(DIR_NAME)
    origin = repo.remote()
    refs = origin.refs

    for ref in refs:
        if ref.remote_head == "master":
            origin.pull(ref.remote_head)

Solution

  • Note the http:// in the url instead of https://4

    As long as you are using an http(s) url, ssh won't come into play at all for authentication.

    You need an ssh url:

    git@github.com:USERNAME/OTHERREPOSITORY.git
    

    An http url would still rely on the username/password authentication scheme.
    Only an ssh url would use your public/private keys.