如何在Git中保存用户名和密码

如何在Git中保存用户名和密码

技术背景

在使用Git进行版本控制时,每次与远程仓库交互(如拉取、推送)都需要输入用户名和密码,这会带来不便。为了提高效率,可以将用户名和密码保存起来,让Git自动使用。不过,不同的保存方法在安全性和便捷性上有所差异。

实现步骤

1. 使用 credential.helper store 方法

这种方法会将凭证以明文形式保存在磁盘的文件中。

  • 运行命令配置Git使用 store 方式保存凭证:
1
git config --global credential.helper store
  • 执行 git pull 操作,输入用户名和密码,之后这些信息就会被记住。凭证会存储在磁盘的文件中,该文件的权限为“仅用户可读/写”,但仍是明文形式。
  • 如果后续要更改密码,再次执行 git pull 会失败,因为密码不正确,Git会从 ~/.git-credentials 文件中移除错误的用户名和密码,然后重新执行 git pull 提供新密码即可。

2. 使用 credential.helper cache 方法

此方法将凭证缓存在内存中一段时间。

  • 基本配置命令:
1
git config --global credential.helper cache

默认情况下,Git会将密码缓存15分钟。

  • 若要更改默认的密码缓存超时时间,可使用以下命令(示例为设置缓存1小时):
1
git config --global credential.helper 'cache --timeout=3600'

3. 使用SSH密钥方法

这是一种安全的认证方式。

  • 生成密钥:
1
ssh-keygen -t rsa -b 4096 -C "[email protected]"

设置保护密钥的密码短语并本地存储。

  • 复制 id_rsa.pub 文件的内容到剪贴板:
1
clip < ~/.ssh/id_rsa.pub
  • 登录到GitHub,进入 Settings -> SSH and GPG keys -> New SSH Key,粘贴密钥并保存。
  • 如果私钥保存为 ~/.ssh/id_rsa,添加它用于认证:
1
ssh-add -K ~/.ssh/id_rsa

4. 使用Git Credential Manager

这是一个安全且用户友好的跨平台解决方案,支持无密码的浏览器OAuth认证。

1
2
3
git-credential-manager configure
git config --global credential.credentialStore cache
git config --global credential.cacheoptions "--timeout 72000"
  • 进行一些可选的配置:
1
2
git config --global credential.guiPrompt false
git config --global credential.gitHubAuthModes browser

核心代码

credential.helper store 配置

1
git config --global credential.helper store

credential.helper cache 配置

1
2
git config --global credential.helper cache
git config --global credential.helper 'cache --timeout=3600'

SSH密钥生成

1
ssh-keygen -t rsa -b 4096 -C "[email protected]"

添加SSH私钥到认证

1
ssh-add -K ~/.ssh/id_rsa

最佳实践

  • 安全性优先:如果对安全性要求较高,建议使用SSH密钥或Git Credential Manager。SSH密钥通过加密的方式进行认证,而Git Credential Manager支持OAuth认证,都能有效保护账户安全。
  • 根据场景选择:如果只是临时使用,或者不想在磁盘上保存凭证,可以选择 credential.helper cache 方法,将凭证缓存在内存中。如果希望长期使用,且对安全性要求不是特别高,可以使用 credential.helper store 方法。
  • 定期更新密码:无论使用哪种方法,都建议定期更新密码,以提高账户的安全性。

常见问题

1. 忘记密码后如何处理?

如果使用 credential.helper store 方法,再次执行 git pull 会失败,Git会移除错误的凭证,然后重新执行 git pull 输入新密码即可。如果使用SSH密钥,需要重新生成密钥并更新到远程仓库。

2. 在不同操作系统上使用有差异吗?

不同操作系统在某些方法的配置上会有差异。例如,在Mac上可以使用 osxkeychain 模式将凭证缓存到系统的钥匙串中;在Windows上可以安装 “Git Credential Manager for Windows” 使用Windows凭证存储。在Linux上,使用Git Credential Manager需要进行一些额外的设置。

3. 如何查看已保存的凭证?

如果使用 credential.helper store 方法,可以查看 ~/.git-credentials 文件。但要注意,该文件中的凭证是明文形式,要妥善保护。


如何在Git中保存用户名和密码
https://119291.xyz/posts/2025-05-13.how-to-save-username-and-password-in-git/
作者
ww
发布于
2025年5月13日
许可协议