1.2. 生成 SSH 密钥对

在本地系统中生成 SSH 密钥对,并将公钥复制到 OpenSSH 服务器以启用无密码登录。每个要创建密钥的用户都必须运行此流程。

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

先决条件

您已经以希望使用密钥连接到 OpenSSH 服务器的用户的身份登录了。

OpenSSH 服务器被配置为允许基于密钥的身份验证。

流程

生成一个 ECDSA 密钥对:

$ ssh-keygen -t ecdsa

Generating public/private ecdsa key pair.

Enter file in which to save the key (/home//.ssh/id_ecdsa):

Enter passphrase (empty for no passphrase):

Enter same passphrase again:

Your identification has been saved in /home//.ssh/id_ecdsa.

Your public key has been saved in /home//.ssh/id_ecdsa.pub.

The key fingerprint is:

SHA256:Q/x+qms4j7PCQ0qFd09iZEFHA+SqwBKRNaU72oZfaCI @

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]-----+

替代方案:Instead of ECDSA,您可以生成:

使用 ssh-keygen 命令(不带任何参数)的 RSA 密钥对

输入 ssh-keygen -t ed25519 命令进行 Ed25519 密钥对

请注意,Ed25519 算法不符合 FIPS-140,OpenSSH 在 FIPS 模式下无法使用 Ed25519 密钥。

将公钥复制到远程机器上:

$ ssh-copy-id @

/usr/bin/ssh-copy-id: INFO: attempting to log in with the new key(s), to filter out any that are already installed

@'s password:

Number of key(s) added: 1

Now try logging into the machine, with: "ssh '@'" and check to make sure that only the key(s) you wanted were added.

@ 替换为您的凭证。

如果不使用 ssh-agent,命令会复制最近修改的 ~/.ssh/id*.pub 公钥。要使用不同的公钥文件,或者首选通过 ssh-agent 存储在内存中的密钥,请使用 ssh-copy-id 命令及 -i 选项。

验证

使用密钥文件登录到 OpenSSH 服务器:

$ ssh -o PreferredAuthentications=publickey @