共计 2304 个字符,预计需要花费 6 分钟才能阅读完成。
最风行的两种 SSH 身份验证机制是基于明码的身份验证和基于公钥的身份验证。应用 SSH 密钥通常比传统的明码身份验证更平安和不便。
环境
客户端:CentOS8 192.168.43.137
服务端:CentOS8 192.168.43.139
创立 SSH 公私钥
通过输出以下命令,生成新的 4096 位的 SSH 密钥对:
[root@localhost ~]# ssh-keygen -t rsa -b 4096
Generating public/private rsa key pair.
Enter file in which to save the key (/root/.ssh/id_rsa):
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in /root/.ssh/id_rsa.
Your public key has been saved in /root/.ssh/id_rsa.pub.
The key fingerprint is:
SHA256:ycOtSDK8ud2kd6EH7OxoQuc1BFb1HJ3T/kvAQJt0LrI root@localhost.localdomain
The key’s randomart image is:
+—[RSA 4096]—-+
| …oo.o o |
| o .+=.+ .|
| . . . +=. o |
| . o.oo .o .|
| + .oSE. . .|
| .*..=o. ..|
| .oo.+o+ . . .|
| .oo== o . |
| .o+ooo |
+—-[SHA256]—–+
在 CentOS8 中设置 SSH 密钥在 CentOS8 中设置 SSH 密钥
想要验证是否生成了新的 SSH 密钥对,应用 ls - l 命令查看~/.ssh 目录是否有方才生成的文件:
[root@localhost ~]# ll ~/.ssh/
total 8
-rw——- 1 root root 3389 May 13 08:26 id_rsa
-rw-r–r– 1 root root 752 May 13 08:26 id_rsa.pub
在 CentOS8 中设置 SSH 密钥在 CentOS8 中设置 SSH 密钥
将公钥复制到近程服务器,应用 ssh-copy-id 实用程序,输出近程服务器的 root 明码:
[root@localhost ~]# ssh-copy-id root@192.168.43.139
/usr/bin/ssh-copy-id: INFO: Source of key(s) to be installed: “/root/.ssh/id_rsa.pub”
The authenticity of host ‘192.168.43.139 (192.168.43.139)’ can’t be established.
ECDSA key fingerprint is SHA256:7O1oIOooh4NZG87aC3v1Zz/vcTXkjOhQBnlkY0CD4y0.
Are you sure you want to continue connecting (yes/no)? yes
/usr/bin/ssh-copy-id: INFO: attempting to log in with the new key(s), to filter out any that are already installed
/usr/bin/ssh-copy-id: INFO: 1 key(s) remain to be installed — if you are prompted now it is to install the new keys
Password:
Number of key(s) added: 1
Now try logging into the machine, with: “ssh ‘root@192.168.43.139′”
and check to make sure that only the key(s) you wanted were added.
在 CentOS8 中设置 SSH 密钥在 CentOS8 中设置 SSH 密钥
也能够应用以下命令复制公钥:
[root@localhost .ssh]# cat ~/.ssh/id_rsa.pub | ssh root@192.168.43.139 “mkdir -p ~/.ssh && chmod 700 ~/.ssh && cat >> ~/.ssh/authorized_keys && chmod 600 ~/.ssh/authorized_keys”
应用密钥登录服务器
应用以下命令登录 ssh 服务器:
[root@localhost ~]# ssh 192.168.43.139
Last login: Tue May 12 12:33:41 2020 from 192.168.43.137
在 CentOS8 中设置 SSH 密钥在 CentOS8 中设置 SSH 密钥
敞开明码认证
登录服务器端,敞开明码认证:
[root@localhost ~]# ssh 192.168.43.139
Last login: Tue May 12 12:33:41 2020 from 192.168.43.137
[root@localhost ~]# vim /etc/ssh/sshd_config
搜寻一下三条,将选项改为 No
PasswordAuthentication no
ChallengeResponseAuthentication no
UsePAM no
在 CentOS8 中设置 SSH 密钥在 CentOS8 中设置 SSH 密钥
重启 sshd 服务:
[root@localhost ~]# systemctl restart sshd
总结
能够应用同一密钥治理多个近程服务器。默认状况下,SSH 的端口是 TCP 22。更改默认 SSH 端口可升高主动攻打的危险。