5.4. 生成 SSH 密钥对

使用这个流程在本地系统中生成 SSH 密钥对,并将生成的公钥复制到 OpenSSH 服务器中。如果正确配置了服务器,您可以在不提供任何密码的情况下登录到 OpenSSH 服务器。

重要

如果以 root 用户身份完成以下步骤,则只有 root 用户可以使用密钥。

流程

  1. 为 SSH 协议的版本 2 生成 ECDSA 密钥对:

    $ ssh-keygen -t ecdsa
    Generating public/private ecdsa key pair.
    Enter file in which to save the key (/home/joesec/.ssh/id_ecdsa):
    Enter passphrase (empty for no passphrase):
    Enter same passphrase again:
    Your identification has been saved in /home/joesec/.ssh/id_ecdsa.
    Your public key has been saved in /home/joesec/.ssh/id_ecdsa.pub.
    The key fingerprint is:
    SHA256:Q/x+qms4j7PCQ0qFd09iZEFHA+SqwBKRNaU72oZfaCI joesec@localhost.example.com
    The key's randomart image is:
    +---[ECDSA 256]---+
    |.oo..o=++        |
    |.. o .oo .       |
    |. .. o. o        |
    |....o.+...       |
    |o.oo.o +S .      |
    |.=.+.   .o       |
    |E.*+.  .  . .    |
    |.=..+ +..  o     |
    |  .  oo*+o.      |
    +----[SHA256]-----+

    您还可以通过输入 ssh-keygen -t ed25519 命令,在 ssh-keygen 命令或 Ed25519 密钥对中使用 -t rsa 选项生成 RSA 密钥对。

  2. 要将公钥复制到远程机器中:

    $ ssh-copy-id joesec@ssh-server-example.com
    /usr/bin/ssh-copy-id: INFO: attempting to log in with the new key(s), to filter out any that are already installed
    joesec@ssh-server-example.com's password:
    ...
    Number of key(s) added: 1
    
    Now try logging into the machine, with: "ssh 'joesec@ssh-server-example.com'" and check to make sure that only the key(s) you wanted were added.

    如果您没有在会话中使用 ssh-agent 程序,上一个命令会复制最新修改的 ~/.ssh/id*.pub 公钥。要指定另一个公钥文件,或在 ssh-agent 内存中缓存的密钥优先选择文件中的密钥,使用带有 -i 选项的 ssh-copy-id 命令。

注意

如果重新安装您的系统并希望保留之前生成的密钥对,备份 ~/.ssh/ 目录。重新安装后,将其复制到主目录中。您可以为系统中的所有用户(包括 root 用户)进行此操作。

验证

  1. 在不提供任何密码的情况下登录到 OpenSSH 服务器:

    $ ssh joesec@ssh-server-example.com
    Welcome message.
    ...
    Last login: Mon Nov 18 18:28:42 2019 from ::1

其他资源

  • ssh-keygen(1)ssh-copy-id(1) 手册页。