私有 github 仓库需认证才能 pip 安装:推荐用 ssh(git+ssh://git@github.com/user/repo.git)或带 pat 的 https(git+https://token@github.com/user/repo.git),严禁硬编码凭证;ci 中优先用 deploy key 或 fine-grained token。

pip install git+https 要求认证,否则报 404 或 Permission denied
直接用 pip install git+https://github.com/username/private-repo.git 会失败——不是网络问题,是 GitHub 拒绝未授权访问。私有仓库默认不接受匿名 HTTPS 请求,git clone 同样会卡在 credential prompt 或直接报错。
必须显式提供凭据。最可靠的方式是用 Personal Access Token(PAT)代替密码(GitHub 已禁用账号密码登录 Git),且 token 需勾选 repo 权限。
- 生成 PAT:GitHub → Settings → Developer settings → Personal access tokens → Tokens (classic) → Generate new token → 勾选
repo→ 生成并复制 - 构造带 token 的 URL:
git+https://<token>@github.com/username/private-repo.git</token> - 执行安装:
pip install git+https://<token>@github.com/username/private-repo.git</token> - 注意:token 泄露风险高,**切勿硬编码在脚本、
requirements.txt或公开仓库中**
用 SSH 方式更安全,但需提前配置本地 SSH key
SSH 协议天然支持私有仓库访问,且无需把 token 暴露在命令行或 URL 中。前提是你的机器已生成 SSH key 并添加到 GitHub 账户(ssh -T git@github.com 应返回成功提示)。
URL 格式为 git+ssh://git@github.com/username/private-repo.git,注意不是 https://,也不是 git@ 开头的简写形式(pip 不识别)。
- 验证 SSH 连通性:
ssh -T git@github.com,看到Hi username! You've successfully authenticated...才算就绪 - 安装命令:
pip install git+ssh://git@github.com/username/private-repo.git - 若遇到
Could not load host key或权限拒绝,检查~/.ssh/config是否配置了Host github.com及对应 IdentityFile - Windows 用户注意:Git for Windows 自带 OpenSSH,但 PowerShell 默认可能调用 Windows OpenSSH(路径不同),建议统一用 Git Bash 执行
CI/CD 环境下推荐用 GITHUB_TOKEN + SSH agent forwarding 或 deploy key
GitHub Actions 等 CI 环境中,GITHUB_TOKEN 有临时读取当前仓库的权限,但**不能跨仓库访问其他私有 repo**。想装另一个私有依赖,得换方式:
- 用 deploy key:为被依赖的私有仓库单独生成一个 SSH key,添加为 deploy key(勾选 “Allow write access” 仅当需要推送时),并在 CI 中注入私钥内容(base64 编码后解码写入
~/.ssh/id_rsa) - 用 GitHub App token 或 fine-grained token:比 classic PAT 更细粒度,可限定只读特定仓库,适合多租户场景
- 避免在
requirements.txt写死 token 或私钥;改用环境变量拼接 URL(如pip install git+https://${GITHUB_TOKEN}@github.com/...),并在 CI 中设 secret - 注意:某些 CI(如 GitLab CI)默认不启用 SSH agent,需手动
eval $(ssh-agent)并ssh-add
常见错误:pip install -e . 失败但 git clone 成功
即使你已用 SSH 或 token 克隆成功,运行 pip install -e . 仍可能报 subprocess.CalledProcessError: command 'git' returned non-zero exit status 128。这是因为 pip install -e . 在构建过程中会重新执行 git 命令(比如读取 commit hash),而当前环境不一定复用了之前的认证上下文。
- 确保
git config --global url."https://".insteadOf git://之类重写规则没干扰 SSH 路径 - 如果
setup.py或pyproject.toml中用了setuptools_scm,它会在安装时调用git describe,此时也要保证 git 认证可用 - 临时解决:先
git clone到本地目录,再cd进去执行pip install -e .,比直接 pip install git+xxx 更稳定 - 根本规避:在私有仓库的
setup.cfg或pyproject.toml中禁用 SCM 版本自动推导,显式写死version = "0.1.0"











