Linux · 免密登录

原理

客户端自己生成公钥私钥,然后将客户端公钥保存到服务器 ~/.ssh/authorized_keys 文件中,以后服务器都会接受客户端传过来的会话经过密钥加密过的公钥,然后解密得到公钥之后和本地 authorized_keys 配置的公钥是否相等,如果是则允许登陆。

img

操作步骤

  • 获取客户端公钥
1
2
$ cat ~/.ssh/id_rsa.pub
ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQCl2+HlmepzqPUlJv+ESCtaYKD2pyUXlEEmmEaw5yTLv09FqD38NzaZZAmnptzOArTO/VzYX5TtNHQPpR0HApid2xMYDrF4C2BpdudobjfiJf4Mx/nzqRPbjTMNzWZJgct9iRl3lR5E9iiwiVxzOJErsaq8Dt4VoUtqVd2t5kocd5g3lvZ4b9/7ogVgLWfudtiiahx9XP3mMn7AdxnnonvSCYI/MVGIvrZAk+1Ss/0UBhgsCqGiUfaqjXfoZoJcOVCSccwl83ZXIqmLtxch46+A0YGWl/dVQSusHTJoMqmJjPm8FfyX8Cn8FaduMA4A8+RzRuox2psgjX/7Q/qg1QCF root@p-cosmo-hce

如果不存在,通过 ssh-keygen 生成密钥对

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
$ ssh-keygen
Generating public/private rsa key pair.
Enter file in which to save the key (/root/.ssh/id_rsa):
/root/.ssh/id_rsa already exists.
Overwrite (y/n)? y
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:4qHMkrfb8bchDuoYV1DjGFy3JYzegeCidBa5yRvmBAU root@CSB-service-2
The key's randomart image is:
+---[RSA 2048]----+
| Eo++o++o . |
| . oo=ooo+ |
| .+o*..... |
|..oO .. . |
|. + o + S |
| * + o |
| + * + . . |
| * + = ... |
| ..=.. o... |
+----[SHA256]-----+
You have mail in /var/spool/mail/root
  • 将公钥保存到服务端
1
2
vi ~/.ssh/authorized_keys
ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQCl2+HlmepzqPUlJv+ESCtaYKD2pyUXlEEmmEaw5yTLv09FqD38NzaZZAmnptzOArTO/VzYX5TtNHQPpR0HApid2xMYDrF4C2BpdudobjfiJf4Mx/nzqRPbjTMNzWZJgct9iRl3lR5E9iiwiVxzOJErsaq8Dt4VoUtqVd2t5kocd5g3lvZ4b9/7ogVgLWfudtiiahx9XP3mMn7AdxnnonvSCYI/MVGIvrZAk+1Ss/0UBhgsCqGiUfaqjXfoZoJcOVCSccwl83ZXIqmLtxch46+A0YGWl/dVQSusHTJoMqmJjPm8FfyX8Cn8FaduMA4A8+RzRuox2psgjX/7Q/qg1QCF root@p-cosmo-hce
  • 测试是否可以登录
1
2
3
4
5
6
7
ssh root@10.138.225.12
The authenticity of host '10.138.225.12 (10.138.225.12)' can't be established.
ECDSA key fingerprint is SHA256:CL0QyyLYaWQDl+Gkf4NjI1Q4p9M05XM02avppepLn9k.
ECDSA key fingerprint is MD5:55:3a:a1:2c:21:7f:24:3c:65:df:d4:41:5c:e5:7e:b2.
Are you sure you want to continue connecting (yes/no)? yes
Warning: Permanently added '10.138.225.12' (ECDSA) to the list of known hosts.
Last login: Tue Dec 3 10:12:34 2019 from 10.138.16.192

如果出现报错信息 ssh_exchange_identification: read: Connection reset by peer,服务端执行:

1
echo "sshd:10.x.*.*" >> /etc/hosts.allow