如何在 CentOS/RHEL 上设置 SSH 密钥以实现无密码ssh登录

本文说明了在 2 个 CentOS/RHEL 主机之间配置无密码 ssh 的步骤。
尽管所有 Linux 发行版的步骤略有变化,但这些步骤几乎保持不变。

  1. 以我们要设置 ssh 密钥的用户身份登录,在本例中,我们使用用户“geek”。

  2. 创建私钥和公钥:

$ ssh-keygen
Generating public/private rsa key pair.
Enter file in which to save the key (/home/geek/.ssh/id_rsa):
Created directory '/home/geek/.ssh'.
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in /home/geek/.ssh/id_rsa.
Your public key has been saved in /home/geek/.ssh/id_rsa.pub.
The key fingerprint is:
SHA256:joc/+DIFmDiSD9qc/ZuF5I/iA1ghBK+f3niOnbfYFrk geek@node01
The key's randomart image is:
+---[RSA 2048]----+
|+.               |
|...              |
| o.o o           |
|+.+ o .          |
|oO +  .oS        |
|o.*..oo=.        |
|  o. .==+        |
| . =++EB.        |
|  ++B=**+.       |
+----[SHA256]-----+

说明:

我们可以在 ssh-keygen 上指定一个选项,例如大小和类型。
有关 man ssh-keygen 的更多信息

-b 位

指定要创建的密钥中的位数。
对于 RSA 密钥,最小大小为 768 位,默认为 2048 位。
通常,2048 位就足够了。
DSA 密钥必须正好是 FIPS 186-2 指定的 1024 位。

-t 类型

指定要创建的密钥类型。
协议版本 1 的可能值为“rsa1”,协议版本 2 的可能值为“dsa”、“ecdsa”或者“rsa”。

  1. 新密钥将位于 /home/geek/.ssh 。
    移动到 .ssh 目录创建密钥并验证:
$ cd .ssh
$ ls
id_rsa id_rsa.pub
  1. 将公钥复制到目标服务器(node02)
$[geek@node01 .ssh]$ ssh-copy-id -i id_rsa.pub geek@node02
/bin/ssh-copy-id: INFO: Source of key(s) to be installed: "id_rsa.pub"
The authenticity of host 'node02 (192.168.1.12)' can't be established.
ECDSA key fingerprint is SHA256:PJplQZl2GQqpoJDK7d4nubIP65/A6YyKBGSSaObvzXo.
ECDSA key fingerprint is MD5:a1:53:e6:d8:9a:71:47:ba:86:a1:d5:d2:25:4c:7c:3b.
Are you sure you want to continue connecting (yes/no)? yes
/bin/ssh-copy-id: INFO: Source of key(s) to be installed: "id_rsa.pub"
/bin/ssh-copy-id: INFO: attempting to log in with the new key(s), to filter out any that are already installed
/bin/ssh-copy-id: INFO: 1 key(s) remain to be installed -- if you are prompted now it is to install the new keys
geek@node02's password:
Number of key(s) added: 1
Now try logging into the machine, with "ssh 'geek@node02'"
and check to make sure that only the key(s) you wanted were added.
  1. 现在测试密钥,我们应该直接登录目标服务器。
[geek@node01 .ssh]$ ssh geek@node02
[geek@node02 ~]$

注意:如果服务器尚未安装 openssh-clients 软件包,另一种选择是:

$ cat id_rsa.pub | ssh user@node02 "cat >> ~/.ssh/authorized_keys"
日期:2020-09-17 00:13:54 来源:oir作者:oir