您可以使用在本地系统上生成的 SSH 密钥对,并将生成的公钥复制到 OpenSSH 服务器来在不输入密码的情况下登录到 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/
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in /home/
Your public key has been saved in /home/
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]-----+
$ ssh-keygen -t ecdsa
Generating public/private ecdsa key pair.
Enter file in which to save the key (/home/
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in /home/
Your public key has been saved in /home/
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]-----+
Copy to Clipboard
Copied!
Toggle word wrap
Toggle overflow
您还可以使用没有任何参数的 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
…
Number of key(s) added: 1
Now try logging into the machine, with: "ssh '
$ 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
…
Number of key(s) added: 1
Now try logging into the machine, with: "ssh '
Copy to Clipboard
Copied!
Toggle word wrap
Toggle overflow
将
如果您没有在会话中使用 ssh-agent 程序,上一个命令会复制最新修改的 ~/.ssh/id*.pub 公钥。要指定另一个公钥文件,或在 ssh-agent 内存中缓存的密钥优先选择文件中的密钥,使用带有 -i 选项的 ssh-copy-id 命令。
验证
使用密钥文件登录到 OpenSSH 服务器:
ssh -o PreferredAuthentications=publickey
$ ssh -o PreferredAuthentications=publickey
Copy to Clipboard
Copied!
Toggle word wrap
Toggle overflow
其他资源
您系统上的 ssh-keygen (1) 和 ssh-copy-id (1) 手册页