我使用Git已经有一段时间了,但不断的密码请求开始让我感到很烦。

我使用的是Mac OS X和GitHub,我按照GitHub的设置Git页面的指示设置Git和SSH密钥。

我还将github SSH密钥添加到了我的Mac OS X密钥链中,正如github的SSH密钥密码页面中提到的那样。我的公钥已在Git中注册。

然而,每次我尝试Git拉时,我都必须输入用户名和密码。除了SSH密钥之外,我是否需要为此设置其他东西?


当前回答

我认为您可能有错误的Git存储库URL。

打开.git/config并找到[remote“origin”]部分。确保您使用的是SSH:

ssh://git@github.com/username/repo.git

如果单击克隆或下载并选择SSH,您可以在存储库的主页面中看到SSH URL。

而不是https或git:

https://github.com/username/repo.git
git://github.com/username/repo.git

现在,您可以只使用SSH密钥而不是用户名和密码进行验证。

如果Git抱怨已经添加了'origin',请打开.config文件,将[remote origin]后面的url=“…”部分编辑为url=ssh://github/username/repo.git


其他服务也是如此。确保地址如下:protocol://something@网址

例如,Azure DevOps的.git/config:

[remote "origin"]
    url = https://mystore@dev.azure.com/mystore/myproject/
    fetch = +refs/heads/*:refs/remotes/origin/*

其他回答

我想你解决了你的问题,但我看不到能帮我的解决方案,所以就在这里。

键入终端:

echo "" > ~/.ssh/known_hosts

这将清空known_hosts文件,您必须添加您使用过并连接到的每个主机,但这解决了问题。

步骤1:检查当前配置

cat .git/config

您将获得:

[core]
    repositoryformatversion = 0
    filemode = true
    bare = false
    logallrefupdates = true
    ignorecase = true
    precomposeunicode = true
[remote "origin"]
    url = https://github.com/path_to_your_git.git
    fetch = +refs/heads/*:refs/remotes/origin/*
[user]
    name = your_username
    email = your_email
[branch "master-staging"]
    remote = origin
    merge = refs/heads/master-staging

步骤2:删除远程源

git remote rm origin

步骤3:使用用户名和密码添加远程源

git remote add origin https://your_git_username:your_git_password@github.com/path_to_your_git.git

面临着同样的问题。

请确保已正确设置远程原点:

$git remote add origin master "https://...git " 

我觉得static_rtti提供的答案在某种意义上很粗糙。我不知道这是否在早期可用,但Git工具现在提供了凭据存储。

缓存模式

$ git config --global credential.helper cache

使用“缓存”模式将凭据保存在内存中一段时间。没有一个密码存储在磁盘上,15分钟后将从缓存中清除。

存储模式

$ git config --global credential.helper 'store --file ~/.my-credentials'

使用“存储”模式将凭据保存到磁盘上的纯文本文件中,它们永远不会过期。

我个人使用的是商店模式。我删除了存储库,克隆了它,然后必须输入一次凭据。

参考:7.14 Git工具-凭证存储

git config credential.helper store

注意:虽然这很方便,但Git会将您的凭据以明文形式存储在项目目录下的本地文件(.Git凭据)中(请参见下面的“home”目录)。如果不喜欢,请删除此文件并切换到使用缓存选项。

如果您希望Git恢复到每次需要连接到远程存储库时都向您请求凭据,可以运行以下命令:

git config --unset credential.helper

要将密码存储在%HOME%目录(而不是项目目录)中的.git凭据中,请使用--global标志

git config --global credential.helper store