openssh实现key验证免密码登录

实验:实现openssh key验证###

实验前准备:
   两台已经安装了openssh的Centos,主机A的IP地址为172.22.52.16,主机B的IP地址为172.22.52.17。

步骤一:首先在A机器生成密钥对,命令:ssh-keygen,生成的秘钥默认会保存在家目录的.ssh/下id_rsa和id_rsa.pub),设置密钥对密码,这里不设置了全部回车跳过

[19:16:09root@localhost data]#ssh-keygen
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:esARTVf53owszvSNjetiqWF4qcrzSMISX/TB+J0gsAg root@localhost.localdomain
The key's randomart image is:
[19:16:58root@localhost data]#ls -a ~/.ssh
.  ..  id_rsa  id_rsa.pub

步骤二:将客户端的公钥(id_rsa.pub)拷贝到服务端(B主机)上root的家目录(因为我要登录的是root用户)并命名为authorized_keys,方法有好几种,我就使用最方便的一个:ssh-copy-id,这个命令会自己在相应的目录生成authorized_keys文件,当然也可以用scp等等拷贝过去。

[19:56:12root@localhost ~]#ssh-copy-id -i id\_rsa.pub root@172.22.52.17          
/usr/bin/ssh-copy-id: INFO: Source of key(s) to be installed: "/root/.ssh/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@172.22.52.17's password:  #输入主机B登录密码以完成公钥拷贝

Number of key(s) added: 1

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

步骤三:当客户端再次发送一个连接请求,包括ip、用户名;服务端得到客户端的请求后,会到authorized_keys中查找,如果有响应的IP和用户,就会随机生成一个字符串,服务端将使用客户端拷贝过来的公钥进行加密,然后发送给客户端,得到服务端发来的消息后,客户端会使用私钥进行解密,然后将解密后的字符串发送给服务端,服务端接受到客户端发来的字符串后,跟之前的字符串进行对比,如果一致,就允许免密码登录了

[19:57:02root@localhost ~]#ssh root@172.22.52.17
Last login: Tue Apr 16 13:03:58 2019 from 172.22.52.16
[18:04:36root@m9l ~]#exit
logout
Connection to 172.22.52.17 closed.

Ps:第二步如果出现下面这个错误是因为id_rsa.pub命令只在当前工作目录寻找公钥文件,进入.ssh/目录或指定公钥绝对路径即可解决

[19:54:29root@localhost ~]#ssh-copy-id -i id_rsa.pub root@172.22.52.17

/usr/bin/ssh-copy-id: ERROR: failed to open ID file 'id_rsa.pub': No such file or directory
posted @ 2019-04-22 00:42  绿鲤鱼与理理与驴  阅读(2041)  评论(0编辑  收藏  举报