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

以上

相关推荐
qq_5470261791 天前
Git 使用指南
git
wzfj123451 天前
ssh 远程pc如何不用每次都输入密码
github
XiaoHu02071 天前
Linux多线程(详细全解)
linux·运维·服务器·开发语言·c++·git
*才华有限公司*1 天前
RTSP视频流播放系统
java·git·websocket·网络协议·信息与通信
juelianhuayao1 天前
Git错误提交后如何快速删除本次commit
git
chen<>1 天前
Git原理与应用
大数据·git·elasticsearch·svn
行百里er1 天前
代码跑得慢?让Spring的StopWatch告诉你真相!
java·后端·github
小兔崽子去哪了1 天前
Git 专题
git
金米kk1 天前
git pull时报错Your local changes to the following files would…的解决办法
git
超级罗伯特1 天前
git一次性完成仓库下载及所有分支获取
git·git仓库拉取