免登陆 安全密钥验证

加密是对信息进行编码和解码的技术,它通过一定的算法(密钥)将原本能被直接阅读的明文信息转换成密文形式。

密钥即是密文的钥匙,有私钥和公钥之分。

在传输数据时,如果担心被他人监听或截获,就可以在传输前先使用公钥对数据加密处理,然后再进行传送。这样,只有掌握私钥的用户才能解密这段数据,除此之外的其他人即便截获了数据,一般也很难将其破译为明文信息。

1、在需要免登陆的节点生成“密钥对”。(192.168.10.20)

[root@Client ~]# ssh-keygen    //默认算法是rsa,也可使用-t指定算法
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.   //此时将自动生成.ssh目录和id_rsa id_rsa.pub两个文件
The key fingerprint is:
SHA256:kHa7B8V0nk63evABRrfZhxUpLM5Hx0I6gb7isNG9Hkg root@linuxprobe.com
The key's randomart image is:
+---[RSA 2048]----+
|          o.=.o.+|
|       . + =oB X |
|      + o =oO O o|
|     . o + *.+ ..|
|      .ES . + o  |
|     o.o.=   + . |
|      =.o.o . o  |
|     . . o.  .   |
|        ..       |
+----[SHA256]-----+

[root@Client.ssh]# ll /root/.ssh/
total 12
-rw-------. 1 root root 1831 Dec 1 19:12 id_rsa

-rw-r--r--. 1 root root 401 Dec 1 19:12 id_rsa.pub //本机公钥
-rw-r--r--. 1 root root  175 Dec  1 19:16 known_hosts

2、将生成的公钥文件(id_ras.pub)传送到需要免登陆的目标主机。

[root@Client ~]# ssh-copy-id 192.168.10.10  //此命令会自动在目标主机(192.168.10.10)创建/root/.ssh/authorized_keys文件且将id_rsa.pub写入其中,如果目标主机已经存在authorized_keys文件,会将id_rsa.pub追加到文件中。
/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.10.10's password: 此处输入服务器管理员密码

Number of key(s) added: 1

Now try logging into the machine, with:   "ssh '192.168.10.10'"
and check to make sure that only the key(s) you wanted were added.
---------------也可使用scp传输--------------
[root@Client ~]#scp /root/.ssh/id_rsa.pub root@192.168.10.10:/root/.ssh/ //将本地文件推送到目标主机
[root@Server ~]#cat /root/.ssh/id_rsa.pub  >> /root/.ssh/authorized_keys  //在目标主机上将公钥文件写入authorized_keys
---------------也可使用scp传输--------------

[root@server ~ ]# ls -l /root/.ssh/    //此时目标主机authorized_keys文件中已经存储了id_rsa.pub

total 8
-rw-------. 1 root root 802 Dec 3 18:48 authorized_keys
-rw-r--r--. 1 root root 525 Dec 3 18:53 known_hosts

此时192.168.10.20即可免密登录到192.168.10.10(其基本原理是.10主机authorized_keys文件中存储了.20的id_rsa.pub,.20机器才能免密登录到.10)

注:如果多台机器之间都需要免密登录的话,就需要在authorized_keys文件中相互存储id_rsa.pub。





原文地址:https://www.cnblogs.com/wushuai2018/p/15637311.html