1. 问题背景
在自动化测试环境中推送代码时,origin 原本配置为 HTTPS 地址:
bash
https://github.com/XXX/ProjiectName.git
该环境没有交互式终端,无法手动输入账号密码,也没有安装 gh 或配置 credential helper,因此执行 git push 时报错:
text
could not read Username for 'https://github.com'
2. 先确认 SSH 可用
本机已有密钥 ~/.ssh/id_ed25519,并且执行:
bash
ssh -T git@github.com
返回了 Hi githubname,说明 GitHub 已识别这把公钥,SSH 通道可用。
3. 改 remote 再用 SSH 推送
将 remote 地址从 HTTPS 切换为 SSH 格式:
bash
git remote set-url origin git@github.com:XXX/ProjiectName.git
git push -u origin HEAD
Git 改走 git@github.com:...,使用 SSH 密钥完成认证,推送成功。
4. 与 HTTPS 的差异对比
| 对比项 | HTTPS | SSH |
|---|---|---|
| 地址形态 | https://github.com/业主/仓库.git |
git@github.com:业主/仓库.git |
| 认证方式 | Token / 密码 / credential helper | ~/.ssh 私钥 |
| 本场景表现 | 无凭据 → 失败 | 已有密钥且已加入 GitHub → 成功 |
5. 注意事项
git remote set-url只修改当前仓库的 remote URL,不会改动全局 git config 中的用户名、邮箱等设置。- 切换后,在本仓库内执行
git push/git pull都会默认走 SSH。 - 若后续仍需使用 HTTPS,需要配置 Personal Access Token,或安装并登录
gh。