SSH公鑰登錄原理(參考:https://www.cnblogs.com/scofi/p/6617394.html):
主要有兩種登錄方式:第一種爲密碼口令登錄,第二種爲公鑰登錄
一、密碼口令登錄
通過密碼進行登錄,主要流程爲:
1、客戶端連接上服務器之後,服務器把自己的公鑰傳給客戶端
2、客戶端輸入服務器密碼通過公鑰加密之後傳給服務器
3、服務器根據自己的私鑰解密登錄密碼,如果正確那麼就讓客戶端登錄
二、公鑰登錄
公鑰登錄是爲了解決每次登錄服務器都要輸入密碼的問題,流行使用RSA加密方案,主要流程包含:
1、客戶端生成RSA公鑰和私鑰
2、客戶端將自己的公鑰存放到服務器
3、客戶端請求連接服務器,服務器將一個隨機字符串發送給客戶端
4、客戶端根據自己的私鑰加密這個隨機字符串之後再發送給服務器
5、服務器接受到加密後的字符串之後用公鑰解密,如果正確就讓客戶端登錄,否則拒絕。這樣就不用使用密碼了。
理解了原理之後配置就很簡單了,以下使用環境爲EHEL 7 系統
一、Linux端的配置
1、客戶端生成密鑰,傳送到服務器:
[root@localhost ~]# 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: //再次確認密碼
[root@localhost ~]# cat .ssh/id_rsa.pub //查看生成的公鑰信息
[root@localhost ~]# cat .ssh/id_rsa //查看生成密鑰信息
2、將生成的公鑰傳送到服務器:
[root@localhost ~]# ssh-copy-id 192.168.10.10
A key fingerprint is e4:bd:ba:43:01:23:ae:67:05:aa:d3:85:c5:78:60:68.
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
[email protected]'s password: //輸入遠程服務器的root密碼
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.
3、服務器端無需任何操作就可以不使用密碼ssh遠程服務器了。
[root@localhost ~]# ssh 192.168.10.10
二、windows端使用xshell工具(或用puttygen生成密鑰)
4、打開Xshell軟件,點擊菜單欄的工具 > 用戶密鑰管理者 > 生成,彈出生成密鑰對話框,默認即可,點擊下一步:
5、生成密鑰對完成後,下一步;
6、密鑰名稱先不修改,這裏的密碼是對密鑰進行加密,這樣別人拿到你的密鑰沒有密碼也使用不了,這裏只是做個演示,不修改了,下一步:
7、提示你沒有修改密碼,點擊是,仍然繼續:
8、點擊 保存爲文件 ,把公鑰保存到本地電腦:
9、先遠程Linxu系統,將電腦上的公鑰文件拖至會話窗口,將文件傳送到Linux系統裏:
三、服務器端配置:
10、在root目錄下創建帶有.ssh隱藏屬性的目錄,在Linux端上傳公鑰至服務器會自動創建該目錄,如果已經存在改目錄,這一步跳過:
[root@localhost .ssh]# mkdir /root/.ssh
11、將公鑰文件移動到.ssh/目錄下,因爲在Linux端已上傳了一份公鑰文件(上傳時會自動重命名爲:authorized_keys)到服務器,所以移動公鑰文件的同時必須重命名爲別的名字來與之區別,這裏就重命名爲:authorized_1_keys
[root@localhost ~]# mv id_rsa_2048.pub .ssh/authorized_1_keys
12、因爲公鑰是從windows系統上傳,所以需要修改.ssh目錄下的所有文件與.ssh目錄SElinux上下文的值一致,當然也可以關閉SElinux:
[root@localhost ~]# /sbin/restorecon -Rv /root/.ssh
或:臨時關閉SElinux
[root@localhost ~]# setenforce 0
13、[root@localhost ~]# vim /etc/ssh/sshd_config
1)、增加一行從Windows端上傳過來的公鑰文件(指定文件的路徑):
2)、將78行的使用密碼認證的配置把yes改成no,這樣就僅能使用密鑰這臺服務器。
14、重啓sshd服務並加入開機自啓動:
[root@localhost .ssh]# systemctl restart sshd
[root@localhost .ssh]# systemctl enable sshd
15、這樣不管Linux或Windows端都可以通過SSH遠程Linux的時候使用密鑰登錄: