【Linux】SSH免密登录机制
原理
weekend110
主机请求登录spark01
主机(登录时会带上用户名和主机名)。spark01
主机查看自己的授权列表,发现授权列表中存在weekend110
主机的公钥。spark01
主机使用weekend110
主机的公钥加密一个随机字符串发送给weekend110
主机。weekend110
主机使用公钥对应的私钥解密spark01
主机发过来的密文,解密结果应该就是那个随机字符串。weekend110
主机将解密结果(那个随机字符串)发送给spark01
主机。spark01
主机验证解密结果。spark01
主机告知weekend110
主机通过验证,可以登录。
操作
生成秘钥对
- 在
centos1
主机上生成秘钥对:
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:
68:59:32:f6:12:48:56:25:bd:be:fa:09:6d:ed:84:e9 root@centos1
The key's randomart image is:
+--[ RSA 2048]----+
| o.oo. |
| o . .. |
| . = .. |
| . O. |
| =.S |
| . o.+ |
| . =.o |
| +.+ |
| .oE . |
+-----------------+
秘钥默认生成在主目录下的
.ssh
目录下面。
- 进入到
.ssh
目录:
cd .ssh/
ls -all
总用量 24
drwx------. 2 root root 4096 2月 25 2016 .
dr-xr-x---. 33 root root 4096 9月 8 19:29 ..
-rw-r--r--. 1 root root 1184 2月 25 2016 authorized_keys
-rw-------. 1 root root 1675 9月 8 19:50 id_rsa
-rw-r--r--. 1 root root 394 9月 8 19:50 id_rsa.pub
-rw-r--r--. 1 root root 1591 9月 8 19:30 known_hosts
id_rsa.pub
:公钥
id_rsa
:私钥。
复制公钥
- 使用
scp
远程拷贝命令将id_rsa.pub
拷贝到centos9
主机上
也可以使用
ssh-copy-id
命令:ssh-copy-id centos9
,他会自动将公钥拷贝到authorized_keys
文件中
scp id_rsa.pub centos9:/tmp/
The authenticity of host 'centos9 (10.1.200.149)' can't be established.
RSA key fingerprint is 96:19:d7:7a:2f:d9:39:62:36:1e:6c:72:27:83:df:6c.
Are you sure you want to continue connecting (yes/no)? yes
Warning: Permanently added 'centos9' (RSA) to the list of known hosts.
root@centos9's password:
id_rsa.pub
- 登录
centos9
,查看id_rsa.pub
是否拷贝成功:
ls -all
总用量 66444
drwxrwxrwt. 10 root root 4096 9月 8 20:00 .
dr-xr-xr-x. 26 root root 4096 9月 8 19:13 ..
-rw-r--r--. 1 root root 394 9月 8 20:00 id_rsa.pub
- 加入授权列表,将
id_rsa.pub
添加到centos9
主机上的authorized_keys
文件中:
cd .ssh
ls -all
总用量 24
drwx------. 2 root root 4096 2月 25 2016 .
dr-xr-x---. 33 root root 4096 8月 29 21:26 ..
-rw-r--r--. 1 root root 1184 2月 25 2016 authorized_keys
-rw-------. 1 root root 1675 2月 25 2016 id_rsa
-rw-r--r--. 1 root root 394 2月 25 2016 id_rsa.pub
-rw-r--r--. 1 root root 1197 2月 25 2016 known_hosts
cat /tmp/id_rsa.pub >> authorized_keys
cat authorized_keys
ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAQEAzjVxaAl7Hq4oIwgPNbm9kzHtHmqFP78jGgd7CWkZ3Lvg6CmrjjhNczrdPdUt6WaGqZoEWcbcdHE4MHcv4g8rEyV/CnCSzbnQXhwC6Su8QiO8mrmIufCPY3GTJMj9Q2I6ROZwPI91/eLrsFqhMtucKRFDfy0FOpUPIe2c1XeJaPw7fxLbj0Go0tmwD2sMSuHQ4EqHRuPjOIZUsNbgl+8XnyddkX1s1wOgXqM13B4dn8i0ZRpj1jAAW0VigqR/3MVnG/7IT8zrEuDQyeOQuq5FeYog0/1oc2QD4+dPQwvSotOTtDxur8ZgrwHiVjLpbhh46XnBROPDJ64wt4Ih2h/A0Q== root@centos1
测试
在centos1
主机上直接使用ssh
命令登录centos9
主机:
ssh centos9
Last login: Thu Sep 8 19:30:08 2016 from 10.1.200.77
[root@centos9 ~]#
可以看到此时在centos1
主机上登录centos9
主机不需要输入密码了。
评论区