Mac 本地项目推送至 GitHub 完整指南

第一步:检查本地 SSH 密钥

macOS 默认 SSH 密钥路径为 ~/.ssh/id_rsa(私钥)和 ~/.ssh/id_rsa.pub(公钥)。

查看是否有现有密钥

ls -la ~/.ssh/

如果没有密钥,生成一对:

ssh-keygen -t rsa -b 4096 -C "your_email@example.com"

一路回车使用默认路径即可

复制公钥内容:

cat ~/.ssh/id_rsa.pub

将输出的内容完整复制,前往 GitHub → Settings → SSH and GPG Keys → New SSH Key,粘贴并保存。

第二步:配置 SSH Config(解决 22 端口被封问题)

部分网络环境(公司网络、部分 ISP)会封禁 SSH 默认的 22 端口,导致 git push 失败。通过以下配置使用 443 端口(HTTPS 端口)绕过限制。

编辑 SSH 配置文件:

vi ~/.ssh/config

添加以下内容:

Host github.com

Hostname ssh.github.com

Port 443

User git

IdentityFile ~/.ssh/id_rsa

IdentitiesOnly yes

说明:

Hostname ssh.github.com --- GitHub 提供的 SSH-over-HTTPS 域名

Port 443 --- 走 HTTPS 端口,通常不会被防火墙拦截

IdentityFile --- 指定使用的私钥路径

IdentitiesOnly yes --- 只使用指定的密钥,避免尝试其他密钥导致失败

第三步:测试 SSH 连接

ssh -T git@github.com

成功时会输出:

Hi <你的用户名>! You've successfully authenticated, but GitHub does not provide shell access.

常见错误:

Permission denied (publickey) → 公钥未添加或 SSH config 配置错误

Connection timed out → 检查网络代理设置,或确认 SSH config 中的 Hostname 和 Port 是否正确

第四步:设置远程仓库地址

首次添加远程仓库:

git remote add origin git@github.com:<用户名>/<仓库名>.git

已有远程地址需要修改(从 HTTPS 切换为 SSH):

git remote set-url origin git@github.com:<用户名>/<仓库名>.git

验证远程地址:

git remote -v

预期输出:

origin git@github.com:<用户名>/<仓库名>.git (fetch)

origin git@github.com:<用户名>/<仓库名>.git (push)

第五步:推送代码

首次推送(设置上游分支关联)

git push --set-upstream origin main

后续推送只需:

git push

附录:HTTPS 方式(备选)

如果 SSH 配置遇到问题,可以临时使用 HTTPS 方式:

设置远程地址为 HTTPS

git remote set-url origin https://github.com/\<用户名>/<仓库名>.git

首次推送会要求输入 GitHub 用户名和 Token(不是密码)

git push --set-upstream origin main

GitHub 已废弃密码认证,需使用 Personal Access Token 代替密码。

快速操作清单

1. 生成密钥(如已有则跳过)

ssh-keygen -t rsa -b 4096 -C "your_email@example.com"

2. 复制公钥 → 添加到 GitHub Settings

cat ~/.ssh/id_rsa.pub

3. 配置 SSH(解决 22 端口问题,可选但推荐)

echo '

Host github.com

Hostname ssh.github.com

Port 443

User git

IdentityFile ~/.ssh/id_rsa

IdentitiesOnly yes

' >> ~/.ssh/config

4. 测试连接

ssh -T git@github.com

5. 设置远程地址

git remote add origin git@github.com:<用户名>/<仓库名>.git

6. 推送

git push --set-upstream origin main

相关推荐
逛逛GitHub6 小时前
推荐 11 个本月热门的 GitHub 开源项目,尤其是第 9 个。
github
FungLeo6 小时前
Swift macOS 游戏开发实战|空当接龙 03|使用 Swift 实现可复现的洗牌算法
macos·swift·随机数·fisher-yates·洗牌算法
Name_NaN_None8 小时前
Mac局域网/公网远程控制另一台Mac方法(屏幕共享+远程看看) —— 「小白教程」
macos·屏幕共享·投屏·远程控制电脑·远程控制软件·mac远程控制mac
岳涛8 小时前
ES 9.2 起 ReadOnly 会设 indexing_complete,此前它要单独配
elasticsearch
钱栈up14 小时前
GitHub 热榜上手|T3 Code:手机远程操控 7 款 AI 编程 Agent
typescript·开源·github
`流年づ20 小时前
联邦学习-安全聚合
git·安全·github
CoderYanger1 天前
Java EE 进阶:14.案例综合练习-博客系统(第二弹):博客详情+令牌技术
服务器·前端·spring boot·后端·spring·java-ee·github
喜欢吃燃面1 天前
Git 原理与使用(三):标签、多人协作与 Git Flow 落地
大数据·git·elasticsearch
FungLeo1 天前
Swift macOS 开发实战 01|用 Swift 开发空当接龙,如何定义范围与验收
macos·项目管理·需求分析·swift·游戏开发
喜欢吃燃面1 天前
Git 原理与使用(二):分支是平行宇宙,远程仓库是共享时空
大数据·git·elasticsearch