Git|GitHub SSH 连接配置与验证全流程(通用方法)

如是我闻:

一段时间不用就忘咋配置了,在这里总结一下


🧭 1️⃣ 检查是否安装 Git

在终端输入:

bash 复制代码
git --version

✅ 若返回版本号(如 git version 2.43.0),说明已安装。

若提示找不到命令,执行:

bash 复制代码
xcode-select --install

🔑 2️⃣ 生成新的 SSH Key

执行以下命令(替换为你的邮箱):

bash 复制代码
ssh-keygen -t ed25519 -C "youremail@example.com"

按提示:

复制代码
Enter file in which to save the key (/Users/用户名/.ssh/id_ed25519):
→ 直接按回车(使用默认路径)

Enter passphrase (empty for no passphrase):
→ 直接按回车两次(不设置密码,方便日常使用)

✅ 生成的密钥文件:

复制代码
~/.ssh/id_ed25519       ← 私钥
~/.ssh/id_ed25519.pub   ← 公钥

📋 3️⃣ 查看并复制公钥

bash 复制代码
cat ~/.ssh/id_ed25519.pub

复制输出内容(从 ssh-ed25519 开始到结尾)。


🌐 4️⃣ 在 GitHub 添加公钥

1️⃣ 登录 GitHub

2️⃣ 点击右上角头像 → Settings

3️⃣ 左侧 → SSH and GPG keys

4️⃣ 点击 New SSH key

5️⃣ 填写:

  • Title: MacBook SSH Key
  • Key: 粘贴刚复制的内容
    6️⃣ 保存 ✅

⚙️ 5️⃣ 启动 ssh-agent 并加载密钥

bash 复制代码
eval "$(ssh-agent -s)"
ssh-add ~/.ssh/id_ed25519

🔍 6️⃣ 测试 SSH 是否连通

bash 复制代码
ssh -T git@github.com

预期输出:

复制代码
Hi yourusername! You've successfully authenticated, but GitHub does not provide shell access.

✅ 表示连接成功!


🧾 7️⃣ 关联你的本地仓库

进入项目目录:

bash 复制代码
cd ~/Documents/myproject
git init
git remote add origin git@github.com:yourusername/myproject.git

🚀 8️⃣ 推送测试

bash 复制代码
echo "SSH connection test $(date)" > connection_test.txt
git add .
git commit -m "test: SSH connection successful"
git push -u origin main

若输出:

复制代码
To github.com:yourusername/myproject.git
 * [new branch] main -> main

✅ 表示 SSH + GitHub 已完全连通。


🧠 9️⃣ 常见错误与解决

错误提示 原因 解决办法
Permission denied (publickey) 未加载私钥 / Key 未添加到 GitHub 执行 ssh-add ~/.ssh/id_ed25519 或重新添加公钥
Repository not found 远程地址错误 检查 remote 地址:git remote -v
Could not resolve hostname 网络异常 / GitHub 屏蔽 检查网络、VPN 或 DNS
Permission denied after passphrase prompt 忘记密钥密码 删除旧 key 重新生成无密码 key

✅ 10️⃣ 验证仓库同步状态

bash 复制代码
git remote -v

输出:

复制代码
origin  git@github.com:yourusername/myproject.git (fetch)
origin  git@github.com:yourusername/myproject.git (push)

并确保:

bash 复制代码
git status

输出:

复制代码
On branch main
Your branch is up to date with 'origin/main'.

表示一切同步。


🧩 快速命令汇总(适合复制保存)

bash 复制代码
# 生成 key
ssh-keygen -t ed25519 -C "youremail@example.com"
# 查看公钥
cat ~/.ssh/id_ed25519.pub
# 启动 agent 并添加 key
eval "$(ssh-agent -s)"
ssh-add ~/.ssh/id_ed25519
# 测试连接
ssh -T git@github.com
# 检查远程地址
git remote -v

以上

相关推荐
阿虎儿9 小时前
Git exclude 功能解析
git
独立开阀者_FwtCoder10 小时前
最近做了一个健身小程序:智形健身助手,健身的佬们来提点意见
前端·javascript·github
隔窗听雨眠10 小时前
VS Code Git工作树:多分支并行开发的完整实践方案
git
^yi11 小时前
【Linux系统编程】快速上手git仓库管理,核心三板斧
git
xuefeiniao12 小时前
CentOS + 宝塔服务器偶发 SSH、面板、网站全部无法访问排查记录(PHP-FPM 内存耗尽案例)
服务器·centos·ssh·php
郝同学今天有进步吗12 小时前
构建 LangGraph Code Review Agent(四):文件过滤与 AnalysisPackage 分包
git·python·ai·code review
夕夕木各13 小时前
从第一个 PR 到 Vite 官方中文文档维护者
github·vite
隔窗听雨眠15 小时前
GitHub Actions自动化运维实战:从零构建一体化CI/CD流水线
运维·自动化·github
weixin_4573402116 小时前
ssh 本地链接服务器地址和服务器查看本地地址
运维·服务器·ssh
胖大和尚1 天前
git本地实现local->remote推送
git