跨平台 GitHub SSH 配置指南

一、检查现有 SSH 密钥

ls -al ~/.ssh  

若存在 id_ed25519id_rsa 文件(如 id_rsa.pub),可直接跳到添加公钥步骤


二、生成 SSH 密钥

1. 通用命令(推荐 Ed25519 算法)

ssh-keygen -t ed25519 -C "your_email@example.com"  
  • 参数说明
    • -t ed25519:更安全的新算法(2025 年主流推荐)。
    • -C:注释,建议用 GitHub 注册邮箱。
  • 操作提示
    • 保存路径:直接回车(默认 ~/.ssh/id_ed25519)。
    • 密码设置:可选(增强安全性),回车跳过则无密码。

2. 兼容旧系统(RSA 算法)

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

适用于不支持 Ed25519 的环境(如老版本 Linux)。


三、添加公钥到 GitHub

  1. 复制公钥内容

    # macOS/Linux
    cat ~/.ssh/id_ed25519.pub | pbcopy  # macOS
    cat ~/.ssh/id_ed25519.pub | xclip -sel clip  # Linux(需安装 xclip)
    
    # Windows(Git Bash)
    cat ~/.ssh/id_ed25519.pub > /dev/clipboard  # 或手动打开文件复制。
    
  2. 添加到 GitHub

    • 登录 GitHub → SettingsSSH and GPG KeysNew SSH Key
    • Title:设备标识(如 My-MacBook
    • Key:粘贴复制的公钥内容
    • 点击 Add SSH Key

四、配置 SSH 代理

加载 SSH 代理(如 ssh-agent)的核心目的是简化身份认证流程并提升安全性,尤其在需要频繁使用 SSH 密钥的场景中。

1. 启动代理并加载密钥

eval "$(ssh-agent -s)"  # 启动代理(所有系统通用)

2. 添加私钥到代理

# macOS(永久加载到钥匙串)
ssh-add --apple-use-keychain ~/.ssh/id_ed25519  

# Windows/Linux
ssh-add ~/.ssh/id_ed25519  

macOS 优化:在 ~/.ssh/config 中添加 UseKeychain yes,避免重复输入密码。


五、测试 SSH 连接

ssh -T git@github.com  
  • 成功响应
    Hi username! You've successfully authenticated...  
    
  • 首次连接提示:输入 yes 信任主机。

六、配置 Git 使用 SSH

1. 检查仓库远程 URL

git remote -v  

若显示 https:// 开头,需切换为 SSH:

git remote set-url origin git@github.com:username/repo.git  

2. 全局设置 Git 身份(必做!)

git config --global user.name "Your Name"
git config --global user.email "your_email@example.com"  

此配置与 SSH 密钥独立,用于标识提交者身份。


七、故障排除

1. 权限问题

# macOS/Linux
chmod 700 ~/.ssh
chmod 600 ~/.ssh/id_ed25519  

# Windows(Git Bash)
icacls %USERPROFILE%\.ssh\id_ed25519 /inheritance:r /grant:r "%USERNAME%":(R)  

2. 连接失败

  • 检查公钥是否完整粘贴到 GitHub。
  • 排查防火墙/代理是否阻塞 SSH 端口(22)。
  • 详细日志:ssh -Tv git@github.com

八、高级技巧:多账号管理

  1. 生成第二对密钥
    ssh-keygen -t ed25519 -C "work@email.com" -f ~/.ssh/id_ed25519_work  
    
  2. 配置 ~/.ssh/config
    Host github.com-personal  # 自定义别名
      HostName github.com
      User git
      IdentityFile ~/.ssh/id_ed25519
    
    Host github.com-work      # 工作账号
      HostName github.com
      User git
      IdentityFile ~/.ssh/id_ed25519_work  
    
  3. 使用示例
    git clone git@github.com-work:company/project.git  # 指定工作账号克隆
    

跨平台差异总结

操作 Windows (Git Bash) macOS/Linux
密钥生成 同左 同左
代理加载 每次重启需 ssh-add 钥匙串自动管理
公钥复制 cat > /dev/clipboard pbcopyxclip
权限修复 icacls 命令 chmod 命令

✅ 通过此指南,可实现 Windows/macOS/Linux 三系统统一配置,仅代理加载和权限命令存在差异。


参考资料
[1] Ubuntu 配置 GitHub SSH|[5] SSH 通用配置|[10] GitHub 添加 SSH 密钥|[11] SSH 密钥生成详解