如何为不同的 git repos 设置用户名和密码?

shi*_*ish 29 password git

?[$] cat ~/.gitconfig

[user]
    name = Shirish Agarwal
    email = xxxx@xxxx.xxx
[core]
    editor = leafpad
    excludesfiles = /home/shirish/.gitignore
    gitproxy = \"ssh\" for gitorious.org
[merge]
    tool = meld
[push]
    default = simple
[color]
    ui = true
    status = auto
    branch = auto
Run Code Online (Sandbox Code Playgroud)

现在我想把我的 git 凭据放在 github、gitlab 和 gitorious 上,这样每次我都不必在浏览器上查找凭据。如何做到这一点,所以它是自动化的?

我正在运行 zsh

Ste*_*itt 25

使用 SSH

处理 git 身份验证的常用方法是将其委托给 SSH。通常,您在远程存储库(例如 在 GitHub 上)中设置 SSH 公钥,然后在需要进行身份验证时使用它。您当然可以使用密钥代理,由您的桌面环境处理或手动使用ssh-agentssh-add

为了避免必须指定用户名,您也可以在 SSH 中进行配置,在~/.ssh/config; 例如我有

Host git.opendaylight.org
  User skitt
Run Code Online (Sandbox Code Playgroud)

然后我可以使用克隆

git clone ssh://git.opendaylight.org:29418/aaa
Run Code Online (Sandbox Code Playgroud)

(注意那里没有用户名)。

使用 gitcredentials

如果 SSH 方法不适用(例如,您使用的是通过 HTTPS 访问的存储库),git 确实有自己的处理凭据的方式,使用gitcredentials(通常是git-credential-store)。您指定您的用户名使用

git config credential.${remote}.username yourusername
Run Code Online (Sandbox Code Playgroud)

和凭证助手使用

git config credential.helper store
Run Code Online (Sandbox Code Playgroud)

(指定--global是否要在任何地方使用此设置)。

然后,当您第一次访问存储库时,git 会询问您的密码,并将其存储(默认情况下在 中~/.git-credentials)。对存储库的后续访问将使用存储的密码而不是询问您。


小智 8

对于那些后来发现这个问题的人——我在这方面遇到了困难,最终让它发挥了作用

https/credentials.helper/Ubuntu

  1. 全局取消设置:
    git config --global --unset credentials.helper
  2. 在本地取消设置:(在每个回购中) git config --unset credential.helper
  3. 为每个 repo 创建凭证文件:(在每个 repo 内)

    git config credential.helper 'store --file ~/.git_reponame_credentials'
    
    Run Code Online (Sandbox Code Playgroud)

并不是说这是最好的方法或唯一的方法 - 但经过几个令人沮丧的小时后,它对我有用。

  • @shirish 不是真的,第三点是我需要的 - 指定文件所在位置的选项。 (3认同)