git clone 本身不处理权限,失败源于 https 协议缺乏凭证;应使用 personal access token(https)或配置 ssh 密钥(推荐),并避免硬编码 token。

git clone 命令本身不处理权限,关键在 URL 和凭证
直接运行 git clone https://github.com/username/private-repo.git 会失败,报错类似 fatal: Authentication failed for 'https://github.com/username/private-repo.git/'。这不是命令写错了,而是 Git 拉取时没带合法身份凭证。HTTPS 协议默认走浏览器式登录或 token 认证;SSH 协议则依赖本地私钥匹配远程公钥。
用 HTTPS + Personal Access Token(推荐 GitHub / GitLab)
GitHub 已停用密码认证,必须用 token;GitLab 同理。Token 要勾选 repo 权限(GitLab 是 read_repository)。
- 生成 token 后,把 URL 改成:
https://<token>@github.com/username/private-repo.git</token> - 或者更安全的做法:先配置凭据助手,再用原始 URL:
git clone https://github.com/username/private-repo.git,首次拉取时系统会弹窗或命令行提示输入用户名和 token(用户名填你的账号名,密码栏粘贴 token) - Windows 用户可运行
git config --global credential.helper manager-core;macOS 用git config --global credential.helper osxkeychain;Linux 常用cache或libsecret
用 SSH URL 避免反复输 token
前提是已在 Git 托管平台(如 GitHub)添加了本机的 id_rsa.pub 公钥,且本地 ssh-agent 已加载私钥。
- 确认 SSH 配置就绪:
ssh -T git@github.com应返回 Hi XXX! You've successfully authenticated… - 使用 SSH 地址克隆:
git clone git@github.com:username/private-repo.git - 若私钥不在默认路径(如 ~/.ssh/id_rsa),需在
~/.ssh/config中显式指定:Host github.com IdentityFile ~/.ssh/my_private_key
拉取子目录或特定分支?clone 本身不支持,得后续操作
git clone 总是下载整个仓库历史,不能只拉一个子文件夹。所谓“只克隆某目录”是常见误解,实际需靠 git sparse-checkout 或 svn export 类工具辅助,但代价是失去完整 Git 功能。
- 要拉非默认分支(比如
dev),加-b参数:git clone -b dev https://token@github.com/username/private-repo.git - 想跳过历史节省时间,用浅克隆:
git clone --depth 1 -b dev https://token@github.com/username/private-repo.git,但之后无法切换其他分支或git pull全量更新 - 私有仓库若启用了 2FA 或 SSO,HTTPS token 可能被拒绝,此时 SSH 几乎是唯一稳定选择











