为 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
相关推荐
D2aZXN3FhrDa7e2123 分钟前
佛山乐从低预算实体店如何选择?看美诚AI自动化获客方案
运维·人工智能·自动化·佛山美诚科技有限公司
无足鸟ICT26 分钟前
【RHCA+】查看变量
linux·运维·服务器
Kina_C36 分钟前
Linux DNS 服务器-从高速缓存到辅助 DNS 部署指南
linux·运维·服务器·dns
suaizai_1 小时前
TypeScript 7 正式发布!Vue 暂被 “拒之门外“ !!!
linux·运维·ubuntu
慕伏白2 小时前
【慕伏白】Linux 系统如何根据端口号关闭进程
linux·运维·服务器
letisgo52 小时前
VMware Workstation + Ubuntu 26.04 LTS 小白运维部署手册
linux·运维·ubuntu
蓝创工坊Blue Foundry2 小时前
图片文字提取到 Excel:批量任务如何先定义要交付的字段
运维·服务器·开发语言·数据库·自动化·ocr·excel
Xu_youyaxianshen2 小时前
Git 零基础常用指令手册(Gitee / GitHub 通用 )
git·gitee·github
晚风吹长发2 小时前
Docker使用——Docker容器及相关命令
linux·运维·服务器·docker·容器·架构
ShiXZ2132 小时前
Docker Compose 安装与配置指南
运维·docker·容器