我最近切换到将我的存储库同步到GitHub上的https://(由于防火墙问题),它每次都会要求输入密码。

有没有办法缓存凭据,而不是每次git推送时都进行身份验证?


当前回答

通常你有一个远程URL,像这样,

git remote -v

origin    https://gitlab.com/username/Repo.git (fetch)
origin    https://gitlab.com/username/Repo.git (push)

如果您想在使用git push时跳过用户名和密码,请尝试以下操作:

 git remote set-url origin https://username:password@gitlab.com/username/Repo.git

我刚刚向origin添加了相同的URL(包括密码在内的用户详细信息)。

注意:如果用户名是电子邮件Id,则不起作用。

git remote -v

origin    https://username:password@gitlab.com/username/Repo.git (fetch)
origin    https://username:password@gitlab.com/username/Repo.git (push)

其他回答

如果您正在使用osxkeychain,并且有一个令牌过期,并希望更新它,请执行以下步骤:

在终端中运行,然后按enter键两次。

git credential-osxkeychain erase
 host=github.com
 protocol=https

现在应该会提示您输入用户名/密码。然而,有时这似乎并不“需要”,你必须继续重新进入。

如果是,请重新启动计算机。现在,下次运行git命令并输入用户名/密码时,它将被保存。

您还可以编辑bashrc文件并在其中添加脚本。

这将在您启动Git时询问您的密码一次,然后在您注销之前记住密码。

SSH_ENV=$HOME/.ssh/environment
  
# Start the ssh-agent
function start_agent {
    echo "Initializing new SSH agent..."

    # Spawn ssh-agent
    /usr/bin/ssh-agent | sed 's/^echo/#echo/' > "${SSH_ENV}"
    echo succeeded
    chmod 600 "${SSH_ENV}"
    . "${SSH_ENV}" > /dev/null
    /usr/bin/ssh-add
}
  
if [ -f "${SSH_ENV}" ]; then
     . "${SSH_ENV}" > /dev/null
   ps -ef | grep ${SSH_AGENT_PID} | grep ssh-agent$ > /dev/null || {
      start_agent;
  }
else
    start_agent;
fi

OAuth(身份验证)

您可以创建自己的个人API令牌(OAuth),并以与使用普通凭据相同的方式使用它(位于:/settings/tokens)。例如:

git remote add fork https://4UTHT0KEN@github.com/foo/bar
git push fork

.netrc文件

另一种方法是在~/.netrc(在Windows上为_netrc)中配置用户/密码,例如。

machine github.com
login USERNAME
password PASSWORD

对于HTTPS,添加额外的行:

protocol https

凭据助手

要在使用HTTPS时在Git中缓存GitHub密码,您可以使用凭据助手告诉Git每次与GitHub对话时记住您的GitHub用户名和密码。

Mac:git config--全局凭证.helper osxkeychain(需要osxkeychain助手),Windows:git-config--全局凭据。helper wincredLinux和其他:git-config--全局凭证.helper缓存


相关:

如何在终端密钥链中存储Linux上的GitHub https密码?如何确保Git不会向我索要GitHub用户名和密码?配置Git客户端,如GitHub for Windows,以不要求身份验证将本地回购推送到具有双重身份验证的GitHub回购

您可以使用凭据助手。

git config --global credential.helper 'cache --timeout=x'

其中x是秒数。

我知道这不是一个安全的解决方案,但有时你只需要一个简单的解决方案-而不需要安装任何其他东西。由于helper=store不适合我,我创建了一个虚拟助手:

创建一个脚本并将其放在用户bin文件夹中,此处名为credfake,该脚本将提供您的用户名和密码:

#!/bin/bash
while read line
do
  echo "$line"
done < "/dev/stdin"
echo username=mahuser
echo password=MahSecret12345

使其可执行:

chmod u+x /home/mahuser/bin/credfake

然后在git中配置它:

git config --global credential.helper /home/mahuser/bin/credfake

(或不使用--仅限一个回购协议的全局)

和-voilá-git将使用此用户+密码。