在 GitHub 上添加 SSH 密钥可以让你在推送代码时无需每次都输入用户名和密码,提高效率和安全性。以下是详细的步骤:


第一步:检查是否已有 SSH 密钥

打开终端(Terminal)或 Git Bash(Windows),运行以下命令:

ls -al ~/.ssh

查看是否有以下文件:

  • id_rsaid_rsa.pub(旧版 RSA)
  • id_ed25519id_ed25519.pub(推荐,更安全)

如果已有 .pub 文件,说明你已经有 SSH 密钥,可以跳到第三步。


第二步:生成新的 SSH 密钥

如果没有密钥,运行以下命令生成(使用 ed25519 算法,推荐):

ssh-keygen -t ed25519 -C "your_email@example.com"
  • -t ed25519:指定加密类型(现代、安全)
  • -C "your_email@example.com":添加注释(通常是你的邮箱)

如果你使用旧系统不支持 ed25519,可以用 RSA:

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

按提示操作:

  1. 输入保存路径(直接回车使用默认路径)
  2. 设置密码(可选,建议设置以增强安全)

第三步:启动 SSH Agent

SSH Agent 可以帮你管理密钥,避免重复输入密码。

eval "$(ssh-agent -s)"

然后将密钥添加到 agent:

ssh-add ~/.ssh/id_ed25519

(如果是 RSA,则是 ~/.ssh/id_rsa


第四步:复制 SSH 公钥内容

运行以下命令复制公钥内容到剪贴板:

  • macOS:

    pbcopy < ~/.ssh/id_ed25519.pub
    
  • Windows (Git Bash):

    cat ~/.ssh/id_ed25519.pub | clip
    
  • Linux:

    xclip -sel clip < ~/.ssh/id_ed25519.pub
    

或者直接用 cat 查看内容并手动复制:

cat ~/.ssh/id_ed25519.pub

输出类似:ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAI... your_email@example.com


第五步:在 GitHub 添加 SSH 密钥

  1. 登录 GitHub
  2. 点击右上角头像 → Settings
  3. 左侧菜单选择 SSH and GPG keysNew SSH key
  4. 填写:
    • Title: 比如 My LaptopWork PC
    • Key type: 选择 Authentication
    • Key: 粘贴你复制的公钥内容(必须完整)
  5. 点击 Add SSH key

✅ 成功后你会看到绿色提示。


第六步:测试连接

在终端运行:

ssh -T git@github.com

首次连接会提示确认,输入 yes

如果看到类似:

Hi username! You've successfully authenticated, but GitHub does not provide shell access.

说明配置成功 ✅


常见问题

  • Permission denied (publickey):检查 SSH agent 是否运行,密钥是否正确添加。
  • Agent admitted failure to sign using the key:运行 ssh-add 重新添加密钥。
  • 多个 GitHub 账号:需要配置不同的 SSH 配置文件(~/.ssh/config)。

✅ 总结

  1. 生成密钥 → 2. 启动 agent → 3. 复制公钥 → 4. 添加到 GitHub → 5. 测试连接

完成之后,你就可以用 git clone git@github.com:username/repo.git 进行免密操作了!

Logo

有“AI”的1024 = 2048,欢迎大家加入2048 AI社区

更多推荐