SSH 密钥生成指南

完全教程:学习如何生成、配置和管理 SSH 密钥,支持 Ed25519 和 RSA 两种密钥类型

1

打开终端

打开终端应用程序(Terminal)

2

生成 ED25519 密钥对

运行以下命令生成密钥。生成过程中会询问保存位置,直接回车使用默认路径。然后设置密钥密码(passphrase),可以留空但建议设置。

终端命令
ssh-keygen -t ed25519 -C "your_email@example.com"
💡 passphrase 是保护私钥的额外密码,即使私钥泄露也能提供一层保护。
3

启动 SSH Agent

SSH Agent 用于管理密钥,避免每次使用都要输入密码。

终端命令
eval "$(ssh-agent -s)"
ssh-add ~/.ssh/id_ed25519
4

查看公钥内容

公钥需要添加到远程服务器或 Git 平台(如 GitHub)。

终端命令
cat ~/.ssh/id_ed25519.pub
💡 复制从 ssh- 开头到邮箱结尾的完整内容。
5

添加公钥到远程服务器

使用 ssh-copy-id 命令一键添加公钥到远程服务器。

终端命令
ssh-copy-id user@hostname
6

测试 SSH 连接

验证密钥配置是否成功。

终端命令
ssh -T user@hostname
💡 连接 GitHub 用:ssh -T git@github.com

SSH Config 文件模板生成器

自动生成 ~/.ssh/config 配置文件

~/.ssh/config
Host myserver
  IdentityFile ~/.ssh/id_ed25519
  IdentitiesOnly yes

常用 SSH 命令参考

生成密钥
ssh-keygen -t ed25519 -C "email"

生成 Ed25519 密钥对

查看公钥
cat ~/.ssh/id_ed25519.pub

显示公钥内容用于复制

复制公钥
ssh-copy-id user@host

将公钥添加到远程服务器

启动 Agent
eval "$(ssh-agent -s)"

启动 SSH Agent 后台进程

添加密钥
ssh-add ~/.ssh/id_ed25519

将私钥添加到 SSH Agent

列出密钥
ssh-add -l

列出已加载的密钥

测试连接
ssh -T git@github.com

测试 GitHub SSH 连接

调试连接
ssh -vT user@host

详细模式排查连接问题

查看指纹
ssh-keygen -lf ~/.ssh/id_ed25519.pub

查看公钥指纹

更改密码
ssh-keygen -p -f ~/.ssh/id_ed25519

修改私钥的密码

转换格式
ssh-keygen -p -m PEM -f ~/.ssh/id_rsa

将密钥转换为 PEM 格式

远程端口转发
ssh -R 8080:localhost:80 user@host

远程端口转发到本地

🔒 安全提示与最佳实践

🔑 优先使用 Ed25519

Ed25519 比 RSA 更安全、更快速,密钥更短。除非对方系统不支持,否则优先选择 Ed25519。

🛡️ 设置密钥密码

为私钥设置 passphrase,即使私钥文件泄露,攻击者也无法直接使用。

📁 保护私钥文件

私钥文件权限应设为 600(chmod 600),.ssh 目录权限设为 700。切勿分享私钥。

🔄 定期轮换密钥

建议每 1-2 年更换一次 SSH 密钥,发现泄露时立即更换。

🚫 禁用密码登录

配置好 SSH 密钥后,建议在服务器端禁用密码登录(PasswordAuthentication no)。

📋 不同用途用不同密钥

为 GitHub、工作服务器、个人服务器分别使用不同的密钥,便于管理和撤销。

SSH 密钥生成指南使用说明

主要功能

  • 分步指导 - 逐步引导生成 SSH 密钥对
  • 多平台支持 - Linux/macOS、Windows PowerShell、Git Bash
  • 配置生成 - 自动生成 SSH config 文件模板
  • 命令参考 - 常用 SSH 命令速查

适用场景

  • GitHub/GitLab SSH 认证配置
  • 服务器远程登录免密设置
  • DevOps 自动化部署
  • 多服务器 SSH 管理

常见问题

相关工具