git push 每次都要输入用户名密码怎么办

根治方案是改用 SSH:生成 ssh-keygen 密钥对,公钥添加到 GitHub,仓库远程地址换成 git@github.com:... 形式。继续用 HTTPS 则配置凭据管理器:osxkeychain、Git Credential Manager 等安全凭据助手,并使用 PAT 而非账号密码。

最佳实践
Git 分支协作与合并示意

一劳永逸的办法是换 SSH 协议:生成密钥对、把公钥挂到 GitHub 账号、把仓库远程地址从 https:// 改成 git@github.com: 形式,之后 push 免密。坚持 HTTPS 的话,必须配置凭据管理器缓存,并且 GitHub 早已不接受账号密码,要用个人访问令牌(PAT)当密码。

方案一:切换 SSH(推荐)

# 1. 生成密钥(已有可跳过)
ssh-keygen -t ed25519 -C "your_email@example.com"

# 2. 复制公钥
cat ~/.ssh/id_ed25519.pub
# 到 GitHub → Settings → SSH and GPG keys → New SSH key 粘贴

# 3. 切换远程地址
git remote set-url origin git@github.com:用户名/仓库.git

# 4. 验证
ssh -T git@github.com

方案二:HTTPS + 凭据缓存

# macOS(钥匙串)
git config --global credential.helper osxkeychain

# Windows(Git Credential Manager,随 Git for Windows 自带)
git config --global credential.helper manager

# Linux(临时保存在内存中,也可以配置系统安全凭据助手)
git config --global credential.helper 'cache --timeout=3600'

下次 push 输入一次后就会记住。注意密码栏要填 PAT(GitHub → Settings → Developer settings → Personal access tokens 生成,并只授予目标仓库必需的权限),不是登录密码。

常见问题(FAQ)

Q:怎么看当前用的是 SSH 还是 HTTPS?

git remote -v:git@github.com: 开头是 SSH,https:// 开头是 HTTPS。

Q:PAT 过期了又频繁要密码?

重新生成 PAT 后需要更新缓存:macOS 在"钥匙串访问"搜 github.com 删除旧条目;Windows 在"凭据管理器 → Windows 凭据"删除 git:https://github.com,下次 push 输入新 PAT。

Q:公司代理下 SSH 22 端口不通?

GitHub 支持走 443 端口的 SSH:在 ~/.ssh/config 配置 Host github.com 指向 ssh.github.com 端口 443。

参考资料

获取专属方案

联系我们

加入社区

微信扫码
加入官方交流群

立即体验

在线开通,按量计费,真正的云服务!

立即开始

选择观测云版本

代码托管平台