ssh-keygen生成SSH密钥对的命令行工具
ssh-keygen 是用于生成 SSH 密钥对的命令行工具。根据你提供的示例,我来详细说明它的使用方法:
基本语法
ssh-keygen -t rsa -b 4096 -C "注释"参数说明
| 参数 | 说明 | 示例值 |
|---|---|---|
-t | 指定密钥类型 | rsa, ed25519, ecdsa |
-b | 指定密钥位数 | 4096(RSA 推荐) |
-C | 添加注释(通常是邮箱) | "your_email@example.com" |
常用命令示例
1. 生成 RSA 密钥(你的示例)
# 4096 位 RSA 密钥
ssh-keygen -t rsa -b 4096 -C "zpcarry@gmail.com"
# 或者使用更安全的 ED25519(推荐)
ssh-keygen -t ed25519 -C "zpcarry@gmail.com"2. 指定文件名
# 自定义密钥文件名
ssh-keygen -t rsa -b 4096 -C "zpcarry@gmail.com" -f ~/.ssh/github_key3. 不交互式生成(自动使用默认路径)
# -N 指定密码,-f 指定文件,-q 静默模式
ssh-keygen -t rsa -b 4096 -C "zpcarry@gmail.com" -N "" -f ~/.ssh/id_rsa -q执行过程
当你运行 ssh-keygen 时,会经历以下步骤:
$ ssh-keygen -t rsa -b 4096 -C "zpcarry@gmail.com"
# 1. 选择保存位置(默认:~/.ssh/id_rsa)
Generating public/private rsa key pair.
Enter file in which to save the key (/home/user/.ssh/id_rsa):
# 2. 设置密码短语(可选)
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
# 3. 生成完成
Your identification has been saved in /home/user/.ssh/id_rsa
Your public key has been saved in /home/user/.ssh/id_rsa.pub
The key fingerprint is:
SHA256:xxx... zpcarry@gmail.com生成的文件
- 私钥:
~/.ssh/id_rsa(妥善保管,不要泄露) - 公钥:
~/.ssh/id_rsa.pub(可以添加到 GitHub、GitLab、服务器等)
推荐的最佳实践
# 推荐使用 ED25519(更安全、性能更好)
ssh-keygen -t ed25519 -C "zpcarry@gmail.com"
# 如果需要兼容旧系统,使用 RSA 4096
ssh-keygen -t rsa -b 4096 -C "zpcarry@gmail.com"
# 查看公钥内容
cat ~/.ssh/id_rsa.pub
# 复制公钥到剪贴板(Linux)
cat ~/.ssh/id_rsa.pub | xclip -selection clipboard
# 复制公钥到剪贴板(macOS)
pbcopy < ~/.ssh/id_rsa.pub注意事项
- 私钥安全:永远不要分享私钥文件,公钥可以公开
权限设置:
~/.ssh目录权限应为700,私钥权限应为600chmod 700 ~/.ssh chmod 600 ~/.ssh/id_rsa- 密码短语:建议设置密码短语增加安全性,可以使用
ssh-agent避免重复输入