为 Github 创建本地 .ssh 关联 (RSA 以支持老系统)

生成 SSH 密钥对

打开终端(Linux/macOS)或 Git Bash(Windows),运行以下命令生成 RSA 密钥对:

bash 复制代码
ssh-keygen -t rsa -b 4096 -C "your_email@example.com"
  • -t rsa 指定密钥类型为 RSA。
  • -b 4096 设置密钥长度为 4096 位(兼容老系统可降低至 2048)。
  • -C 添加注释(通常为邮箱)。

按提示选择密钥存储路径(默认 ~/.ssh/id_rsa)和设置密码(可选)。

将 id_rsa 添加到 SSH Agent 的方法

检查 SSH Agent 是否运行

运行以下命令确认 SSH Agent 是否已在后台运行:

bash 复制代码
eval "$(ssh-agent -s)"

若输出类似 Agent pid 12345 表示 Agent 正在运行。

添加私钥到 SSH Agent

使用 ssh-add 命令添加私钥文件(默认路径为 ~/.ssh/id_rsa):

bash 复制代码
ssh-add ~/.ssh/id_rsa

若私钥有密码保护,会提示输入密码。

验证添加结果

通过以下命令查看已加载的密钥列表:

bash 复制代码
ssh-add -l

输出应显示密钥指纹和对应的注释(如 id_rsa)。

将公钥添加到 GitHub

复制公钥内容(默认路径 ~/.ssh/id_rsa.pub):

bash 复制代码
cat ~/.ssh/id_rsa.pub

登录 GitHub,进入 Settings → SSH and GPG keys → New SSH key,粘贴公钥并保存。

测试 SSH 连接

运行以下命令验证配置:

bash 复制代码
ssh -T git@github.com

若提示 You've successfully authenticated 则关联成功。

配置 Git 使用 SSH

若之前使用 HTTPS 克隆仓库,需更新远程 URL:

bash 复制代码
git remote set-url origin git@github.com:username/repo.git

替换 username/repo 为实际仓库路径。

解决兼容性问题

若遇到老系统不支持新格式,可改用传统 PEM 格式生成密钥:

bash 复制代码
ssh-keygen -m PEM -t rsa -b 2048
  • -m PEM 强制使用 PEM 格式(兼容旧版 OpenSSH)。

多密钥管理

若需为不同账户配置多密钥,编辑 ~/.ssh/config 文件:

bash 复制代码
Host github.com-user1
  HostName github.com
  User git
  IdentityFile ~/.ssh/id_rsa_user1

克隆时使用别名:

bash 复制代码
git clone git@github.com-user1:username/repo.git

解决常见问题

密钥权限问题

确保私钥文件权限为 600,目录权限为 700

bash 复制代码
chmod 600 ~/.ssh/id_rsa
chmod 700 ~/.ssh

自动启动 SSH Agent

~/.bashrc~/.zshrc 中添加以下内容实现登录时自动启动 Agent:

bash 复制代码
if [ -z "$SSH_AUTH_SOCK" ]; then
   eval "$(ssh-agent -s)"
   ssh-add ~/.ssh/id_rsa
fi

指定其他密钥路径

若密钥不在默认路径,需指定完整路径:

bash 复制代码
ssh-add /path/to/custom_key
相关推荐
^—app5668666 小时前
游戏运存小启动不起来临时解决方法
运维·服务器
Ujimatsu6 小时前
虚拟机安装Debian 13.x及其常用软件(2026.4)
linux·运维·ubuntu
志栋智能7 小时前
超自动化安全:构建智能安全运营的核心引擎
大数据·运维·服务器·数据库·安全·自动化·产品运营
Edward111111119 小时前
4月28日防火墙问题
linux·运维·服务器
想学后端的前端工程师9 小时前
【补充内外网突然不通的情况】
运维·服务器
面汤放盐9 小时前
何时使用以及何时不应使用微服务:没有银弹
java·运维·云计算
lpfasd1239 小时前
2026年第17周GitHub趋势周报:AI代理工程化与端侧智能加速落地
人工智能·github
子琦啊9 小时前
【算法复习】字符串 | 两个底层直觉,吃透高频题
linux·运维·算法
AOwhisky10 小时前
Kubernetes 学习笔记:集群管理、命名空间与 Pod 基础
linux·运维·笔记·学习·云原生·kubernetes