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_key

3. 不交互式生成(自动使用默认路径)

# -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

注意事项

  1. 私钥安全:永远不要分享私钥文件,公钥可以公开
  2. 权限设置~/.ssh 目录权限应为 700,私钥权限应为 600

    chmod 700 ~/.ssh
    chmod 600 ~/.ssh/id_rsa
  3. 密码短语:建议设置密码短语增加安全性,可以使用 ssh-agent 避免重复输入

标签: none

添加新评论