實驗:實現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