Git push requires username and password

前端 未结 24 2032
灰色年华
灰色年华 2020-11-22 04:14

I cloned a Git repository from my GitHub account to my PC.

I want to work with both my PC and laptop, but with one GitHub account.

When I try to push to or p

24条回答
  •  北海茫月
    2020-11-22 04:37

    When you use https for Git pull & push, just configure remote.origin.url for your project, to avoid input username (or/and password) every time you push.

    How to configure remote.origin.url:

    URL format:
        https://{username:password@}github.com/{owner}/{repo}
    
    Parameters in URL:
    
    * username 
    Optional, the username to use when needed.
    authentication, if specified, no need to enter username again when need authentication. Don't use email; use your username that has no "@", otherwise the URL can't be parsed correctly, * password optional, the password to use when need authentication. If specified, there isn't any need to enter the password again when needing authentication. Tip: this value is stored as plain text, so for security concerns, don't specify this parameter, * e.g git config remote.origin.url https://eric@github.com/eric/myproject

    @Update - using ssh

    I think using ssh protocol is a better solution than https, even though the setup step is a little more complex.

    Rough steps:

    • Create ssh keys using command, e.g ssh-keygen on Linux, on windows msysgit provide similar commands.
    • Keep the private key on the local machine at a proper location, e.g., ~/.ssh. And add it to the ssh agent via ssh-add command.
    • Upload the public key to the Git server.
    • Change remote.origin.url of the Git repository to ssh style, e.g., git@gitlab.com:myaccount/myrepo.git
    • Then when pull or push, there isn't any need to enter the username or password ever.

    Tips:

    • If your ssh key has a passphrase, then you need to input it on first use of the key after each restart of your machine, by default.

    @Update - Switch between https and ssh protocol.

    Simply changing remote.origin.url will be enough, or you can edit repo_home/.git/config directly to change the value (e.g using vi on Linux).

    Usually I add a line for each protocol, and comment out one of them using #.

    E.g.

    [remote "origin"]
            url = git@gitlab.com:myaccount/myrepo.git
            # url = https://myaccount@gitlab.com/myaccount/myrepo.git
            fetch = +refs/heads/*:refs/remotes/origin/*
    

提交回复
热议问题