設定 SSH 通過金鑰登入
金鑰形式登入的原理是:利用金鑰生成器製作一對金鑰——一隻公鑰和一隻私鑰。將公鑰新增到伺服器的某個賬戶上,然後在客戶端利用私鑰即可完成認證並登入。這樣一來,沒有私鑰,任何人都無法通過 SSH 暴力破解你的密碼來遠端登入到系統。此外,如果將公鑰複製到其他賬戶甚至主機,利用私鑰也可以登入。
下面來講解如何在 Linux 伺服器上製作金鑰對,將公鑰新增給賬戶,設定 SSH,最後通過客戶端登入。
1. 製作金鑰對
首先在伺服器上製作金鑰對。首先用密碼登入到你打算使用金鑰登入的賬戶,然後執行以下命令:
[root@centos6 ~]# ssh-keygen #建立金鑰對 Generatingpublic/private rsa key pair. Enter file in which to save the key (/root/.ssh/id_rsa): #預設就行,按enter Created directory '/root/.ssh'. Enter passphrase (empty for no passphrase): #輸入金鑰鎖碼,或留空按enter Enter same passphrase again: #再輸一遍金鑰鎖碼 Your identification has been saved in /root/.ssh/id_rsa. #私鑰 Yourpublic key has been saved in /root/.ssh/id_rsa.pub. #公鑰 The key fingerprint is: 11:c4:31:23:a4:d0:a0:97:f2:d1:3e:51:6a:6c:14:e0 root@centos6 The key's randomart image is: +--[ RSA 2048]----+ | ++oo+o*. | | o *.+ ..+ | |o E O . | | + = . . | | . o S | | . | | | | | | | +-----------------+ [root@centos6~]#
金鑰鎖碼在使用私鑰時必須輸入,這樣就可以保護私鑰不被盜用。當然,也可以留空,實現無密碼登入。
現在,在 root 使用者的家目錄中生成了一個 .ssh 的隱藏目錄,內含兩個金鑰檔案。id_rsa 為私鑰,id_rsa.pub 為公鑰。
2. 在伺服器上安裝公鑰
鍵入以下命令,在伺服器上安裝公鑰:
[root@centos6 ~]# cd .ssh
[root@centos6 .ssh]# cat id_rsa.pub >> authorized_keys
如此便完成了公鑰的安裝。為了確保連線成功,請保證以下檔案許可權正確:
[root@centos6 .ssh]# chmod 600 authorized_keys [root@centos6 .ssh]# chmod 700 ~/.ssh
3. 設定 SSH,開啟金鑰登入功能
編輯 /etc/ssh/sshd_config 檔案,進行如下設定:
[root@centos6 ~]# vim /etc/ssh/sshd_config
RSAAuthentication yes
PubkeyAuthentication yes
另外,請留意 root 使用者能否通過 SSH 登入:
PermitRootLogin yes
當你完成全部設定,並以金鑰方式登入成功後,再禁用密碼登入:
PasswordAuthentication yes
最後,重啟 SSH 服務:
[root@centos6 ~]# service sshd restart
Stopping sshd: [ OK ]
Starting sshd: [ OK ]
[root@centos6 ~]#
4. 將私鑰下載到客戶端,然後轉換為 PuTTY 能使用的格式
使用 WinSCP、SFTP 等工具將私鑰檔案 id_rsa 下載到客戶端機器上。然後開啟 PuTTYGen,單擊 Actions 中的 Load 按鈕,載入你剛才下載到的私鑰檔案。如果你剛才設定了金鑰鎖碼,這時則需要輸入。
載入成功後,PuTTYGen 會顯示金鑰相關的資訊。在 Key comment 中鍵入對金鑰的說明資訊,然後單擊 Save private key 按鈕即可將私鑰檔案存放為 PuTTY 能使用的格式。
今後,當你使用 PuTTY 登入時,可以在左側的 Connection -> SSH -> Auth 中的 Private key file for authentication: 處選擇你的私鑰檔案,然後即可登入了,過程中只需輸入金鑰鎖碼即可。