Linux 免密码登陆及原理

前言

我们常常会遇到这种情况:从服务器A去连接服务器B,经常需要输入服务器B密码,方可连接。再比如,我们在搭建集群(主从节点)的时候,经常就需要通过 ssh 来启动和停止各个节点上的各种守护进程,这就需要在节点之间执行指令的版时候是不需要输入密码的方式,故我们需要配置 ssh 使用权无密码公钥认证的方式

原理

非对称加密算法--RSA加密原理

了解详细算法:https://blog.csdn.net/wjiabin/article/details/85228078

处理机制

  1. 非对称密钥就是一对密钥:公钥和私钥。
  2. 私钥由自己服务器持有,保存在自己本地中,一般在 .ssh 目录下。
  3. 公钥则通过网络传递给对方服务,保存在对方服务中,一般 .ssh 目录下的 authorized_keys 文件。
  4. 通过私钥加密的数据只能由公钥解密,同样用公钥加密的数据也只有用私钥解密。

免密码机制流程图

免密码机制流程图

步骤

创建公钥与私钥

[root@bigdata11 ~]# ssh-keygen -t rsa
Generating public/private rsa key pair.
# 连续按3次确认键
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:
df:66:eb:74:2e:d8:c9:b5:ed:29:00:74:9a:4f:0f:ff root@bigdata11
The key's randomart image is:
+--[ RSA 2048]----+
|                 |
|         . .     |
|        . +      |
|         + o     |
|        S + +    |
|         . + o.  |
|          .+*ooo |
|          .+==.Eo|
|           .o.oo.|
+-----------------

将公钥发送对方服务器

[root@bigdata11 ~]# ssh-copy-id -i /root/.ssh/id_rsa.pub root@bigdata11
/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@bigdata11's password: 

Number of key(s) added: 1

Now try logging into the machine, with:   "ssh 'root@bigdata11'"
and check to make sure that only the key(s) you wanted were added.

验证

[root@bigdata11 ~] ssh bigdata12

如果不用输入密码,则免密码配置成功!相反,如果服务B想免密码服务A, 循环以上步骤即可。

查看免密码服务列表

[root@bigdata11 software]# more ~/.ssh/authorized_keys 
ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQChruuNQh9jiIiOWsl998hz7J9q/bcfUZSlMQzq2Mj1wGCTUWDT7NyjOjTgJuzmh8cETcddRMPzWTfgqNw8lp4/WeVL61y3mrxIxYDypt/p7rQMpjzqifBb8JEiCMEKn
TpkxoCDF9Wf5NYsUJAYwR4NsnZ9aS9iRMC+T57YGxhFOrZoKJZ0rhHOKvV+/JVDk2L7ApWgRLA/ySARgnB7qeo3QE4cVDP7svjN7SGblkXrE3DUNgPY7eAyv+SRtc1wIjE/fYgyXL5RDi/pwN5P8eHpnF9ncfBCtu5u+O
QwGVU+FGSAlTTmldpH7djdwK6IqpLWI01TB5tnGu3GWRkwu3UJ root@bigdata11
ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDR4G8DZYAOA0PJoKIO7u8rgrfzoTuAhsW+8ZBXXyKWcuFi/ck8kQGuGp4jE3G8p0sh28Ua++eEq6bZqIE7YZvT4bxdREBXkHzEGpxWyewM8EFd/hk+/rCX6wjl8b0iH
d6tUkfnaGvBrWbTOQ+z3soq03lUbeBd6D5Bo/s8moAcDPPG02trSJHuTnLWm8/ejfaIneU9dfsqoNqba60doqJIAv+4/fHYOa/KKu4Bm48rY4+lakZ9M05IsQaEaAolDBr2N8YgnO9SJn+SEQCWvammRi0+ocLDkXE+di
CbSoq2kAMHPeZXZBHfjt1OXVXu5I8sYNT2T14IGSJBVoqqnQFB root@bigdata12
上次更新: 2020-5-10 1:34:13 PM