Git SSH 密钥配置指南

(2025 年 4 月更新版)

一、为什么需要 SSH 密钥?

  • 免密登录:无需每次输入密码即可推送 / 拉取代码
  • 安全验证:通过非对称加密技术保障通信安全
  • 多平台支持:适用于 GitHub/GitLab/Bitbucket 等主流平台

二、配置步骤详解

1. 检查现有密钥

bash

ls -al ~/.ssh  # macOS/Linux 系统
dir %USERPROFILE%\.ssh  # Windows 系统

常见密钥文件

  • id_rsa.pub(RSA 算法)
  • id_ed25519.pub(推荐的 ED25519 算法)
  • authorized_keys(已授权的公钥列表)

💡 提示:若已存在密钥但需要更新,可跳过此步骤直接生成新密钥。

2. 生成新 SSH 密钥

bash

# 推荐使用 ED25519 算法(安全性更高)
ssh-keygen -t ed25519 -C "your_email@example.com"

# 若需兼容旧系统,可使用 RSA 算法(2048位及以上)
ssh-keygen -t rsa -b 4096 -C "your_email@example.com"

交互说明

  1. 保存路径:直接回车使用默认路径(~/.ssh/id_ed25519
  2. 密码设置:
    • 建议设置强密码(推荐)
    • 若需免密登录,可留空(安全性降低)

3. 启动 SSH 代理(守护进程)

bash

# macOS/Linux 系统
eval "$(ssh-agent -s)"

# Windows 系统(PowerShell)
Start-Service ssh-agent

4. 添加密钥到代理

bash

# 默认密钥路径
ssh-add ~/.ssh/id_ed25519

# 若密钥路径不同,需指定路径
ssh-add /path/to/your/private_key

❗ 注意:若添加失败,可能需要先修改密钥文件权限:

 

bash

chmod 600 ~/.ssh/id_ed25519

5. 绑定公钥到 Git 平台

复制公钥内容

bash

# macOS 系统
pbcopy < ~/.ssh/id_ed25519.pub

# Linux 系统
xclip -sel clip < ~/.ssh/id_ed25519.pub

# Windows 系统(PowerShell)
Get-Content ~/.ssh/id_ed25519.pub | Set-Clipboard

绑定流程(以 GitHub 为例):

  1. 登录 GitHub → Settings → SSH and GPG keys
  2. 点击 "New SSH key"
  3. 粘贴公钥内容 → 命名 → 保存

6. 验证连接

bash

# GitHub 验证命令
ssh -T git@github.com

# GitLab 验证命令
ssh -T git@gitlab.com

成功提示

plaintext

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

三、高级配置技巧

  1. 多账户管理

    • 创建多个密钥对(如 id_githubid_gitlab
    • 配置 ~/.ssh/config 文件:

      plaintext

      Host github.com
        IdentityFile ~/.ssh/id_github
      Host gitlab.com
        IdentityFile ~/.ssh/id_gitlab
      
  2. 密钥持久化

    • macOS/Linux:将 ssh-agent 加入开机启动
    • Windows:启用 OpenSSH 服务并设置为自动启动

四、常见问题解决

问题现象可能原因解决方案
Permission denied密钥权限错误chmod 600 ~/.ssh/id_ed25519
Agent admitted failure代理未启动重新执行 eval "$(ssh-agent -s)"
Could not resolve hostname网络问题检查 DNS 配置或尝试 ssh -vT git@github.com

五、最佳实践建议

  1. 定期更换密钥(建议每 6 个月一次)
  2. 为不同平台使用不同密钥(降低风险)
  3. 启用密钥密码(配合密码管理器使用)
  4. 禁用密码认证(通过 ~/.ssh/sshd_config 配置)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值