Git默认不记HTTPS密码,推荐用credential.helper cache内存缓存(默认15分钟),安全且免明文;store会明文存密码至.git-credentials,慎用;更优方案是切换SSH协议,一劳永逸。

Git 默认不会记住 HTTPS 协议下的用户名和密码,每次 git push 或 git pull 都要重输,不是 Git 有问题,是你还没告诉它“记下来”。直接执行 git config --global credential.helper store 能立刻见效,但明文存密码在 ~/.git-credentials 里,不推荐日常开发用。
credential.helper cache:内存缓存,安全又够用
这是大多数本地开发场景的首选。凭据只存在内存中,系统重启或超时后自动清除,不落盘,无明文风险。
- 默认缓存 15 分钟:
git config --global credential.helper cache - 设为 1 小时(3600 秒):
git config --global credential.helper 'cache --timeout=3600' - 设为 8 小时(适合全天开发):
git config --global credential.helper 'cache --timeout=28800' - 注意:
cache在 Windows 上需搭配 Git for Windows 自带的git-credential-manager才稳定;纯cache在某些旧版本可能失效
credential.helper store:明文落地,慎用
它会把用户名、密码以明文形式写进 ~/.git-credentials(macOS/Linux)或 %USERPROFILE%\.git-credentials(Windows),下次操作直接读取。方便,但等于把钥匙贴在门上。
- 启用命令:
git config --global credential.helper store - 首次执行
git push后输入一次账号密码,就会自动生成并写入文件 - 文件内容类似:
https://tanpeng%40163.com:123456@git.thextrader.cn(邮箱里的@会被 URL 编码) - 别在公用电脑、CI 机器、或公司策略禁明文存储的环境用这个
为什么 git config --global user.password 不起作用
很多人试过 git config --global user.password "xxx",发现完全没用——因为 Git 根本不读这个配置项。Git 认证流程只走 credential.helper,user.name 和 user.email 只用于 commit 签名,和远程登录无关。
-
user.name是你在git commit里显示的作者名,不是登录用户名 - HTTPS 登录用户名通常是邮箱(如
name@company.com),也可能是短用户名(取决于 Git 服务端配置) - 如果你硬塞了
user.password,它只是个无意义的自定义配置,Git 完全忽略
更推荐的长期方案:换 SSH,一劳永逸
HTTPS + password 永远绕不开“谁保管凭证”这个问题;SSH 密钥则把认证逻辑交给操作系统和 SSH agent,Git 本身不碰密码,也不存口令。
- 生成密钥:
ssh-keygen -t ed25519 -C "your@email.com"(回车用默认路径) - 启动 agent 并加载:
eval "$(ssh-agent -s)"&&ssh-add ~/.ssh/id_ed25519 - 把
~/.ssh/id_ed25519.pub内容粘贴到 Git 平台(GitHub/GitLab/公司 Git 服务)的 SSH Keys 设置页 - 把远程地址从
https://...改成git@host:owner/repo.git:git remote set-url origin git@git.thextrader.cn:team/project.git - 之后所有操作都不再提示输密码(除非你设置了密钥密码且 agent 未缓存)
真正容易被忽略的是:不同 Git 版本对 cache 的实现差异很大,macOS 上新版 Git for Mac 默认启用了 osxkeychain,而 Linux 命令行环境往往得手动配 cache 或装 libsecret;Windows 用户如果用 Git Bash,建议优先用 Git for Windows 自带的 git-credential-manager,它能对接 Windows 凭据管理器,比裸 store 安全得多。


















