密钥登录原理:
就是用户将自己的公钥储存在远程主机上。登录的时候,远程主机会向用户发送一段随机字符串,用户用自己的私钥加密后,再发回来。远程主机用事先储存的公钥进行解密,如果成功,就证明用户是可信的,直接允许登录shell,不再要求输入密码,这和之前的ssh账号密码也没有直接关系。
这种方法要求用户必须提供自己的公钥。如果没有现成的,可以直接用ssh-keygen生成一个:
[root@localhost ~]# hostnamectl set-hostname server
[root@localhost ~]# bash
[root@server ~]# systemctl stop firewalld.service
[root@server ~]# setenforce 0
[root@localhost ~]# hostnamectl set-hostname client
[root@localhost ~]# bash
[root@client ~]# systemctl stop firewalld
[root@client ~]# setenforce 0
setenforce: SELinux is disabled
用ssh-keygen生成一个密钥
[root@server ~]# ssh-keygen
Generating public/private rsa key pair.
Enter file in which to save the key (/root/.ssh/id_rsa):
Created directory '/root/.ssh'.
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:fIsT/cKWHprpZs0fHOendxI+2ih5LXhXf8aatcKy1xg root@server
The key's randomart image is:
+---[RSA 2048]----+
| |
| |
| |
| . . |
| S o . . |
| = = E. .|
| ooBo=o=++|
| oB*++O**O|
| += .*B+*Bo|
+----[SHA256]-----+
将公钥复制到远程系统的正确位置,要输密码登录
[root@client ~]# ssh-copy-id root@192.168.118.100
The authenticity of host '192.168.118.100 (192.168.118.100)' can't be established.
ECDSA key fingerprint is 1b:c1:f1:4b:50:42:c3:03:e3:1c:f6:4f:5a:3b:74:52.
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
root@192.168.118.100's password:
Number of key(s) added: 1
Now try logging into the machine, with: "ssh 'root@192.168.118.100'"
and check to make sure that only the key(s) you wanted were added.
再次ssh目标主机,实现免密登录
[root@server ~]# ssh root@192.168.118.128
Last login: Tue Aug 28 20:19:52 2018 from 192.168.118.1
[root@client ~]#