Git 使用 Ssh 连接 Git Hub 完整教程
Git 使用 SSH 连接 GitHub 完整教程
一、SSH 方式简介
SSH 是 GitHub 推荐的安全连接方式,相比 HTTPS:
-
不需要每次输入账号密码
-
更稳定,不容易出现 connection reset
-
适合长期开发使用
二、检查是否已有 SSH Key
在 CMD 或 Git Bash 执行:
dir %USERPROFILE%.ssh
如果看到以下文件之一,说明已有 SSH Key:
-
id_ed25519
-
id_ed25519.pub
-
id_rsa
-
id_rsa.pub
三、生成 SSH Key(没有才需要)
执行:
ssh-keygen -t ed25519 -C "你的GitHub邮箱"
一路回车即可(不要设置密码也可以)
默认生成位置:
C:\Users\你的用户名.ssh\
四、启动 SSH Agent
执行:
ssh-agent
如果 Windows 环境需要手动启动服务(管理员 PowerShell):
Set-Service -Name ssh-agent -StartupType Automatic
Start-Service ssh-agent
五、添加 SSH Key 到代理
执行(以 ed25519 为例):
ssh-add %USERPROFILE%.ssh\id_ed25519
成功会提示:
Identity added
六、复制公钥
执行:
type %USERPROFILE%.ssh\id_ed25519.pub
复制输出的整段内容(ssh-ed25519 开头)
七、添加到 GitHub
打开 GitHub SSH Key 页面:
https://github.com/settings/keys
点击:New SSH key
填写:
Title:随便写(如 My PC)
Key:粘贴公钥内容
点击保存
八、测试 SSH 是否成功
执行:
ssh -T git@github.com
第一次会提示:
Are you sure you want to continue connecting? (yes/no)
输入:yes
成功后显示:
Hi 用户名! You've successfully authenticated
九、修改 Git 远程仓库为 SSH
进入项目目录:
cd 项目路径
执行:
git remote set-url origin git@github.com:用户名/仓库名.git
十、确认远程地址
git remote -v
正确结果示例:
origin git@github.com:username/repo.git (fetch)
origin git@github.com:username/repo.git (push)
十一、推送代码
git push
或首次推送:
git push -u origin main
十二、常见问题说明
-
如果 ssh 连接失败:
检查是否执行 ssh -T git@github.com 测试成功 -
如果提示 Permission denied:
说明 SSH Key 没加到 GitHub 或 ssh-agent 未加载 -
如果 push 失败:
确认 remote 是否已从 https 改为 git@github.com
结束
SSH 配置成功后,后续 push/pull 都无需再配置