Git 配置 SSH Key 连接 GitHub 详细教程
前言
在往 github 上 push 项目的时候,如果走 https 的方式,每次都需要输入账号密码,非常麻烦。而采用 ssh 的方式,就不再需要输入,只需要在 github 自己账号下配置一个 ssh key 即可。
配置 SSH
1. 检查是否已有 SSH Key
在 Git Bash(Windows) 、终端(Linux/macOS) 运行以下命令:
# 查看是否已存在密钥
ls -al ~/.ssh
如果看到以下文件,说明已有密钥:
- id_rsa(私钥)
- id_rsa.pub(公钥)
可以跳到第 4 步直接添加到 GitHub
2. 生成新的 SSH Key(如果没有)
# 生成新的 SSH 密钥
ssh-keygen -t rsa -b 4096 -C "[这里输入你的邮箱]"
参数说明:
-t rsa:使用 RSA 算法-b 4096:密钥长度 4096 位(比默认 2048 位更安全)-C "邮箱":密钥的注释标识(通常是你的 GitHub 绑定邮箱)
系统会询问以下问题:
Enter file in which to save the key(~/.ssh/id_rsa)(默认回车)- 直接回车,使用默认路径(推荐)
- 如果已有密钥,可以换个名字,如 id_rsa_github
- Enter passphrase (输入密码,可以为空)建议直接回车(否则每次使用 SSH 都要输入密码)
生成成功后,会在 ~/.ssh/ 目录下创建两个文件:
~/.ssh/id_rsa # 私钥(不要分享)
~/.ssh/id_rsa.pub # 公钥(需要添加到 GitHub/GitLab)
执行过程:
Generating public/private rsa key pair.
Enter file in which to save the key (/c/Users/yaoheng/.ssh/id_rsa): [直接按 Enter]
Enter passphrase (empty for no passphrase): [输入密码或直接回车]
Enter same passphrase again: [再次输入密码或回车]
3. 启动 SSH Agent 并添加密钥
# 启动 SSH agent(用于管理密钥)
eval ""
ssh-add ~/.ssh/id_rsa
ssh-add -l


