乐闻世界logo
搜索文章和话题

How can i save username and password in git?

8 个月前提问
4 个月前修改
浏览次数114

5个答案

1
2
3
4
5

您可以使用 git config在 Git 中启用凭据存储。

shell
git config --global credential.helper store

运行此命令时,第一次从远程存储库拉取或推送时,系统会询问您用户名和密码。

之后,为了与远程存储库进行后续通信,您不必提供用户名和密码。

存储格式是 .git-credentials文件,以明文形式存储。

此外,您还可以使用其他帮助程序 git config credential.helper,即内存缓存:

shell
git config credential.helper 'cache --timeout=<timeout>'

它需要一个可选的 timeout parameter,确定凭证将在内存中保留多长时间。使用帮助程序,凭据将永远不会接触磁盘,并将在指定的超时后被删除。该 default值为900 秒(15 分钟)。


警告:如果您使用此方法,您的 Git 帐户密码将以_明文_格式保存在 中 global .gitconfig file,例如在 Linux 中将是 /home/[username]/.gitconfig.

如果您不希望这样做,请改用 ssh key您的帐户。

2024年6月29日 12:07 回复

注意:此方法将以****明文形式将凭据保存在您的 PC 磁盘上。您计算机上的每个人都可以访问它,例如恶意 NPM 模块。

跑步

shell
git config --global credential.helper store

然后

shell
git pull

提供用户名和密码,稍后将记住这些详细信息。凭证存储在磁盘上的文件中,磁盘权限为“仅用户可读/可写”,但仍为明文形式。

如果您想稍后更改密码

shell
git pull

会失败,因为密码不正确,git然后从~/.git-credentials文件中删除有问题的用户+密码,所以现在重新运行

shell
git pull

提供一个新密码,以便它像以前一样工作。

2024年6月29日 12:07 回复

推荐且安全的方法:SSH

按照以下步骤生成密钥:更多详细信息

shell
$ssh-keygen -t rsa -b 4096 -C "yourEmail@something.com"

设置保护密钥的密码并将其存储在本地

将 id_rsa.pub 文件的内容复制到剪贴板以进行下一步

shell
$ clip < ~/.ssh/id_rsa.pub

转到github.com →_设置_→ SSH 和 GPG 密钥_→_新 SSH 密钥。粘贴密钥并保存

如果私钥在_~/.ssh/目录中保存为__id_rsa_,我们将其添加用于身份验证,如下所示:

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

更安全的方法:缓存

我们可以使用git-credential-cache将我们的用户名和密码缓存一段时间。只需在 CLI(终端或命令提示符)中输入以下内容:

shell
git config --global credential.helper cache

您还可以设置超时时间(以秒为单位),如下所示:

shell
git config --global credential.helper 'cache --timeout=3600'
2024年6月29日 12:07 回复

打开凭据助手,以便 Git 会将您的密码在内存中保存一段时间:

在终端中,输入以下内容:

shell
# Set Git to use the credential memory cache git config --global credential.helper cache

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

要更改默认密码缓存超时,请输入以下内容:

shell
# Set the cache to timeout after 1 hour (setting is in seconds) git config --global credential.helper 'cache --timeout=3600'

来自GitHub 帮助

2024年6月29日 12:07 回复

您可以编辑该~/.gitconfig文件来存储您的凭据

shell
nano ~/.gitconfig

哪个应该已经有

shell
[user] email = your@email.com user = gitUSER

您应该在此文件的底部添加以下内容。

shell
[credential] helper = store

我推荐此选项的原因是因为它是全局的,如果您在任何时候需要删除该选项,您知道该去哪里更改它。

仅在您的个人计算机上使用此选项。

然后当你拉| 克隆| 输入你的Git密码,一般情况下,密码会以~/.git-credentials以下格式保存

shell
https://gituser:gitpassword@domain.xxx

其中 DOMAIN.XXX 可以是 github.com、bitbucket.org 或其他

请参阅文档

重新启动您的终端。

2024年6月29日 12:07 回复

你的答案