使用 Git 1.7.9 及更高版本
自 Git 1.7.9(2012 年 1 月下旬发布)以来,Git 中有一个简洁的机制可以避免在 HTTP / HTTPS 上一直输入密码,称为 credential helpers。 (感谢dazonic 在下面的 cmets 中指出这个新功能。)
使用 Git 1.7.9 或更高版本,您只需使用以下凭证助手之一:
git config --global credential.helper cache
credential.helper cache value 告诉 Git 将您的密码缓存在内存中特定数量的 分钟。默认为 15 分钟,您可以设置更长的超时时间:
git config --global credential.helper "cache --timeout=3600"
将缓存设置为 1 小时,或者:
git config --global credential.helper "cache --timeout=86400"
1 天。如果需要,您还可以永久存储您的凭据,请参阅下面的其他答案。
GitHub 的帮助 also suggests,如果您在 Mac OS X 上并使用 Homebrew 安装 Git,您可以使用本机 Mac OS X 密钥库:
git config --global credential.helper osxkeychain
对于 Windows,有一个名为 Git Credential Manager for Windows 或 wincred in msysgit 的助手。
git config --global credential.helper wincred # obsolete
Git for Windows 2.7.3+(2016 年 3 月):
git config --global credential.helper manager
对于 Linux,您将使用(2011 年)gnome-keyring(或其他密钥环实现,例如 KWallet)。
现在(2020 年),那将是(在 Linux 上)
Fedora
sudo dnf install git-credential-libsecret
git config --global credential.helper /usr/libexec/git-core/git-credential-libsecret
Ubuntu
sudo apt-get install libsecret-1-0 libsecret-1-dev
cd /usr/share/doc/git/contrib/credential/libsecret
sudo make
git config --global credential.helper /usr/share/doc/git/contrib/credential/libsecret/git-credential-libsecret
使用 1.7.9 之前的 Git 版本
对于 1.7.9 之前的 Git 版本,这个更安全的选项不可用,您需要更改您的 origin 远程使用的 URL 以以这种方式包含密码:
https://you:password@github.com/you/example.git
...换句话说,:password 在用户名之后和@ 之前。
你可以为你的origin远程设置一个新的URL:
git config remote.origin.url https://you:password@github.com/you/example.git
确保您使用https,并且您应该知道,如果您这样做,您的 GitHub 密码将以明文形式存储在您的.git 目录中,这显然是不可取的。
任何 Git 版本(嗯,从 0.99 版开始)
另一种方法是将您的用户名和密码放在您的~/.netrc 文件中,尽管与将密码保存在远程 URL 中一样,这意味着您的密码将以纯文本形式存储在磁盘上,因此更少安全且不推荐。但是,如果您想采用这种方法,请将以下行添加到您的 ~/.netrc:
machine <hostname> login <username> password <password>
... 将<hostname> 替换为服务器的主机名,将<username> 和<password> 替换为您的用户名和密码。还要记住对该文件设置限制性文件系统权限:
chmod 600 ~/.netrc
请注意,在 Windows 上,此文件应称为 _netrc,您可能需要定义 %HOME% 环境变量 - 更多详细信息请参阅: