在 Linux 系统中为 Git 添加 SSH 密钥


在 Linux 系统中为 Git 添加 SSH 密钥的步骤如下:

1. 检查现有 SSH 密钥

ls -al ~/.ssh

查看是否已存在密钥文件(如 id_rsaid_ed25519 等)

2. 生成新的 SSH 密钥

# 使用 RSA 算法(推荐)
ssh-keygen -t rsa -b 4096 -C "your_email@example.com"

# 或者使用更现代的 Ed25519 算法
ssh-keygen -t ed25519 -C "your_email@example.com"

生成过程中会提示:

  • 选择保存位置(直接回车使用默认位置)
  • 设置密码(可选,增加安全性)

3. 启动 SSH 代理并添加密钥

# 启动 SSH 代理
eval "$(ssh-agent -s)"

# 将 SSH 私钥添加到代理
ssh-add ~/.ssh/id_rsa

4. 复制公钥到剪贴板

# 显示公钥内容并手动复制
cat ~/.ssh/id_rsa.pub

# 或者使用命令复制到剪贴板(如果系统支持)
xclip -sel clip < ~/.ssh/id_rsa.pub
# 或者
cat ~/.ssh/id_rsa.pub | xclip

5. 将公钥添加到 Git 服务商

GitHub:

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

GitLab:

  1. 登录 GitLab → Preferences → SSH Keys
  2. 粘贴公钥内容

Gitee/GitCode 等:
在对应的设置中找到 SSH 密钥管理页面添加

6. 测试连接

ssh -T git@github.com
# 或对于 GitLab
ssh -T git@gitlab.com

如果看到欢迎信息,说明配置成功。

7. 配置 Git 用户信息(如未设置)

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

可选配置

如果需要为不同的 Git 服务使用不同的密钥,可以在 ~/.ssh/config 文件中配置:

# 创建或编辑配置文件
nano ~/.ssh/config

添加内容:

Host github.com
    HostName github.com
    User git
    IdentityFile ~/.ssh/id_rsa_github

Host gitlab.com
    HostName gitlab.com
    User git
    IdentityFile ~/.ssh/id_rsa_gitlab

这样就完成了 Git SSH 密钥的添加和配置!

posted @ 2025-10-15 14:24  guanyubo  阅读(87)  评论(0)    收藏  举报