温馨提示×

CentOS SSH密钥怎么生成

小樊
54
2026-08-03 03:04:23
栏目: 智能运维

CentOS 上生成 SSH 密钥一般使用 ssh-keygen 命令,步骤如下:


一、生成 SSH 密钥(默认方式)

  1. 打开终端,登录到 CentOS 系统
  2. 执行:
ssh-keygen

按提示操作:

  • 密钥保存路径(默认即可):

    Enter file in which to save the key (/root/.ssh/id_rsa):
    

    直接回车

  • 设置密码(passphrase)

    Enter passphrase (empty for no passphrase):
    

    可直接回车(不设置密码),或输入一个安全密码

  • 确认密码

    Enter same passphrase again:
    

二、生成的文件说明

默认会在 ~/.ssh/ 目录下生成两个文件:

~/.ssh/id_rsa      # 私钥(不要泄露)
~/.ssh/id_rsa.pub  # 公钥(可放到服务器)

查看公钥内容:

cat ~/.ssh/id_rsa.pub

三、将公钥添加到远程服务器(免密登录)

方法 1:使用 ssh-copy-id(推荐)

ssh-copy-id user@remote_ip

示例:

ssh-copy-id root@192.168.1.100

输入一次远程服务器密码即可。


方法 2:手动复制公钥

  1. 本地查看公钥:

    cat ~/.ssh/id_rsa.pub
    
  2. 登录远程服务器,编辑:

    mkdir -p ~/.ssh
    vi ~/.ssh/authorized_keys
    
  3. 将公钥内容粘贴进去

  4. 设置权限(非常重要):

    chmod 700 ~/.ssh
    chmod 600 ~/.ssh/authorized_keys
    

四、测试免密登录

ssh user@remote_ip

如果不再需要输入密码,说明配置成功 ✅


五、生成指定类型或长度的密钥(可选)

生成 ed25519 密钥(更安全、推荐)

ssh-keygen -t ed25519

生成 4096 位 RSA 密钥

ssh-keygen -t rsa -b 4096

六、常见问题排查

1. 权限问题导致无法登录

chmod 700 ~/.ssh
chmod 600 ~/.ssh/authorized_keys

2. SELinux 影响(CentOS 常见)

restorecon -Rv ~/.ssh

3. SSH 服务未开启

systemctl status sshd
systemctl start sshd
systemctl enable sshd

如果你需要 CentOS 7 / 8 / Stream 的专门说明,或者 Windows 生成密钥后上传到 CentOS,可以继续问我。

0