Git 远程仓库认证 & SSH 配置操作指南(Windows + macOS)_git重置.ssh
Git 远程仓库认证 & SSH 配置操作指南(Windows + macOS)
适用场景:解决 Git 推送时出现的认证失败问题,或配置 SSH 免密推送。
一、HTTPS 认证失败问题修复
问题现象
- 执行
git push
时提示:remote: Incorrect username or password (access token)fatal: Authentication failed for \'https://gitee.com/xxx.git/\'
解决方案(Windows & macOS 通用)
1. 确保使用正确的凭据
- Gitee/GitHub 等平台可能要求:
- 私人访问令牌(Access Token) 代替密码(如果开启了两步验证)。
- 令牌需有
push
权限。
2. 清除旧的 Git 凭据
-
Windows:
- 打开 凭据管理器(
Win + R
→ 输入control.exe /name Microsoft.CredentialManager
)。 - 删除
git:https://gitee.com
或类似条目。
- 打开 凭据管理器(
-
macOS:
- 打开 钥匙串访问(command+空格输入“Keychain Access”) → 搜索
gitee.com
或git
。 - 删除相关条目。
- 打开 钥匙串访问(command+空格输入“Keychain Access”) → 搜索
-
Linux/macOS 终端:
git credential-cache exit # 清除缓存# 或手动删除凭据文件rm ~/.git-credentials
3. 重新推送(输入正确的用户名和令牌)
git push
- 密码框输入私人令牌(不是账户密码)。
二、配置 SSH 免密推送(推荐)
1. 生成 SSH 密钥
Windows/macOS/Linux 通用命令
ssh-keygen -t ed25519 -C \"your_email@example.com\"
- 按回车使用默认路径(
~/.ssh/id_ed25519
)。 - 可选:设置密钥密码(直接回车跳过)。
-t ed25519
:指定密钥类型(比默认的 RSA 更安全)。-C \"你的邮箱\"
:添加注释(一般用邮箱,可选)。
(可选)传统 RSA 密钥
ssh-keygen -t rsa -b 4096 -C \"your_email@example.com\"
2. 添加公钥到 Gitee/GitHub
-
复制公钥内容:
cat ~/.ssh/id_ed25519.pub
- 输出类似:
ssh-ed25519 AAAAC3NzaC... your_email@example.com
- 输出类似:
-
粘贴到代码平台:
- Gitee:设置 → SSH 公钥 → 粘贴并保存。
- GitHub:Settings → SSH and GPG keys → 粘贴并保存。
3. 测试 SSH 连接
ssh -T git@gitee.com # Giteessh -T git@github.com # GitHub
- 成功响应:
Hi xxx! You\'ve successfully authenticated, but GITEE.COM does not provide shell access.
4. 切换 Git 远程仓库到 SSH
git remote set-url origin git@gitee.com:SeanJin_Lee/shortlink.git
- 验证是否切换成功:
git remote -v
- 正确输出:
origin git@gitee.com:xxx.git (fetch)origin git@gitee.com:xxx.git (push)
- 正确输出:
5. 推送代码(无需密码)
git push -u origin main
三、常见问题排查
1. 仍提示 Permission denied (publickey)
- 原因:SSH 密钥未加载。
- 解决:
eval \"$(ssh-agent -s)\" # 启动 ssh-agentssh-add ~/.ssh/id_ed25519 # 添加私钥
2. 多个平台的 SSH 密钥管理
在 ~/.ssh/config
中配置(示例):
Host gitee.com HostName gitee.com User git IdentityFile ~/.ssh/gitee_key # 专属密钥Host github.com HostName github.com User git IdentityFile ~/.ssh/github_key
3. 首次推送需关联分支
git push -u origin main # -u 表示关联本地与远程分支
四、总结
ssh-keygen -t ed25519 -C \"邮箱\"
ssh -T git@gitee.com
git remote set-url origin git@gitee.com:xxx.git
git push -u origin main
✅ 完成!以后推送无需输入密码。