前言
首先實作基于密鑰方式登入系統的原理:
- 在用戶端建立一對密鑰對,然後把公鑰放在需要通路的目标伺服器上,另外,還需要把私鑰放在用戶端用來登入的使用者的家目錄下。
- 當用戶端發起登入請求時,會将公鑰檔案送給伺服器端,然後伺服器會做比對兩個公鑰,如果比對成功,會向用戶端發送一個質詢(該質詢是用傳輸密鑰對中的公鑰加密)。
- 客戶度收到這個質詢之後,會進行解密,然後将解密的結果發送給伺服器端确定。
案例:實作密鑰方式登入系統
規劃:
server:10.220.5.113
client:10.220.5.112
第一步:在用戶端器端建立一個密鑰對
# ssh-keygen -t rsa
Generating public/private rsa key pair.
Enter file in which to save the key (/root/.ssh/id_rsa): #詢問1:密鑰對的儲存位置
Created directory '/root/.ssh'.
Enter passphrase (empty for no passphrase): #詢問2:對密鑰對加密密碼
Enter same passphrase again: #詢問3:确認密碼
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:
7d:e7:f4:ef:63:0b:26:fc:90:04:fd:d5:b6:e2:51:a4 [email protected]
The key's randomart image is:
+--[ RSA 2048]----+
| . |
| . o .|
| . . E oo|
| .. . o..|
| S ...+o. |
| o.o+o. |
| = +. .|
| = .o.|
| ..o=|
+-----------------+
# 三次詢問均保持預設,按enter即可;
# ls ~/.ssh/ <<<檢視生成的密鑰對
id_rsa id_rsa.pub
第二步:傳送公鑰到伺服器端主機
# ssh-copy-id -i /root/.ssh/id_rsa.pub [email protected]
The authenticity of host '10.220.5.113 (10.220.5.113)' can't be established.
RSA key fingerprint is 5c:ae:6f:5e:a7:2f:bf:cb:27:fc:c9:a1:46:27:78:d1.
Are you sure you want to continue connecting (yes/no)? yes(此處詢問是否确定繼續連接配接,輸入yes确認)
Warning: Permanently added '10.220.5.113' (RSA) to the list of known hosts.
[email protected]'s password: (輸入用戶端對應使用者的登入密碼)
Now try logging into the machine, with "ssh '[email protected]'", and check in:
.ssh/authorized_keys
to make sure we haven't added extra keys that you weren't expecting.
說明:
- -i:指定要傳輸的密鑰檔案
- [email protected]:指定傳輸到哪個主機上面
- 傳遞到目标主機之後,公鑰檔案會被重命authorized_keys,該檔案的權限必須600
第三步:在10.220.5.113主機上确認公鑰檔案是否傳輸到位:
[[email protected] ~]# ls -l /root/.ssh/
total 4
-rw------- 1 root root 394 Oct 21 01:39 authorized_keys
測試:在用戶端可以直接登入伺服器端
# ssh 10.220.5.113
#ip addr show <<<檢視是否已經登入113主機
------做運維之前很矯情的小年輕-----