我们ssh连接到某台linux主机时,需要输入账号密码。为了免密码登录,我们通常使用SSH Key认证的方式。原理大概如下:
我们要从A主机ssh登录到B主机,通常我们在A主机上生成密钥对,然后将A主机的公钥传到B主机的某个账户家目录下的.ssh/authorized_keys文件中。比如我们需要从A主机上的root账户下用B主机的root账号来登录B主机,则需要将A主机上root账号的公钥传到B主机的root账户下的authorized_keys文件中。
实验环境:
主机A:172.16.206.132
主机B:172.16.206.131
1、首先在A主机上生成密钥对:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
root@JMXCLIENT:~/.
ssh
# ssh-keygen -t rsa
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:
82:6d:c4:a8:84:d4:f9:5f:05:42:c9:e5:64:0a:cb:c9 root@JMXCLIENT
The key's randomart image is:
+--[ RSA 2048]----+
| .. ..ooo=. |
|.. ooo+o* . |
|. . oEo. .. |
| . . = . |
| . . = S |
| . o |
| |
| |
| |
+-----------------+
|
查看生成的文件,注意文件权限
1
2
3
4
5
6
|
root@JMXCLIENT:~/.
ssh
# ll
total 16
-rw-r--r-- 1 root root 392 Feb 17 01:02 authorized_keys
-rw------- 1 root root 1675 Jun 14 21:36 id_rsa
-rw-r--r-- 1 root root 396 Jun 14 21:36 id_rsa.pub
-rw-r--r-- 1 root root 1976 Jun 14 21:19 known_hosts
|
id_rsa:私钥文件
id_rsa.pub:公钥文件
authorized_keys:存放其他主机上的公钥文件,实现SSH 认证的
known_hosts:ssh登录过的主机
2、将A主机的公钥传到B主机的root账户下
此操作需要输入B主机上root用户的密码
1
2
3
4
5
6
7
8
9
|
ssh
-copy-
id
-i ~/.
ssh
/id_rsa
.pub root@172.16.206.131
The authenticity of host
'172.16.206.131 (172.16.206.131)'
can't be established.
RSA key fingerprint is 74:d8:e6:2a:9e:86:22:a7:1e:82:01:f5:79:0d:35:5a.
Are you sure you want to
continue
connecting (
yes
/no
)?
yes
Warning: Permanently added
'172.16.206.131'
(RSA) to the list of known hosts.
root@172.16.206.131's password:
Now try logging into the machine, with
"ssh 'root@172.16.206.131'"
, and check
in
:
.
ssh
/authorized_keys
to
make
sure we haven
't added extra keys that you weren'
t expecting.
|
注意:上面的方法等效于直接在B主机的root账户的/root/.ssh/目录下创建authorized_keys文件,然后将A主机的公钥复制到这个文件中。注意文件的权限。
3、登录B主机查看authorized_keys文件,可以看到A主机的root账户的公钥
1
2
|
[root@localhost .
ssh
]
# cat authorized_keys
ssh
-rsa AAAAB3NzaC1yc2EAAAABIwAAAQEAsZOYbiGl5zu1BNETCDNJQryHIwz1rVgE
/Bhp/dWpJBHTUkTASWBdAe9AP85ADe5rXtjt9atFkXZ/v4O8e2C8fPyY1qXaGcTq2qaB1x62SVrsYvL0eE3TEr0T7eIIC3I1540t/NNe4Tc6ao5/kC
+NOFJPfFNqQ+UOdZTdkuHWsCZqd0aFLrXkgLaMe1ZFhBeG54ncmZ6heAbmbtpmc19qrPY9C8HY5FsV851MMjRvMohRiAMvB0JuHrneJwRKQ3OJLsgm4gDs3rfDj1cjveLzFSihsikVB9XKGmPquoY5BfZ2zQo6Mu3OwJ+5lhbe9ObSCoC9bkZnTJd9Rwz2sUlEiQ== root@JMXCLIENT
|
4、从A主机ssh登录B主机
1
2
|
root@JMXCLIENT:~
# ssh root@172.16.206.131
Last login: Thu Jun 16 11:05:21 2016 from 172.16.206.1
|
A主机登录B主机无需输入密码,直接可以登录。
扩展:从上面的案例我们可以知道谁想要SSH连接到其他主机,则需要在本机上生成密钥对,然后将公钥传到对方账户下的authorized_keys文件中即可。但是如果假设有这样一种情况,现在有很多个主机,都想要SSH登录A主机,但是不希望在每一台主机上都创建密钥对,怎么办呢?
可以将A主机的私钥文件拷贝到每台主机上面,然后A主机的公钥拷贝到A主机的authorized_keys文件中,这样A主机拿公钥,其他主机拿私钥,就可以实现SSH key认证了。
总结:SSH Key认证很灵活,只要密钥对是匹配的,就可以实现认证,不管这个密钥对是由谁生成的。