Linux配置使用SSH Key登入並禁用root密碼登入
阿新 • • 發佈:2019-09-06
Linux系統大多數都支援OpenSSH,生成公鑰、私鑰的最好用ssh-keygen命令,如果用putty自帶的PUTTYGEN.EXE生成會不相容OpenSSH,從而會導致登入時出現server refused our key錯誤。
1、root使用者登陸後,執行以下第一句指令,其他根據提示進行輸入:
ssh-keygen -t rsa 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: #重複密碼短語 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: 05:71:53:92:96:ba:53:20:55:15:7e:5d:59:85:32:e4 root@test The key's randomart image is: +--[ RSA 2048]----+ | o o .. | | . o oo.+ . | | o.+... = | | ...o | | o S | | . | | | | | | | +--------------------+
此時在/root/.ssh/目錄下生成了2個檔案,id_rsa為私鑰,id_rsa.pub為公鑰。私鑰自己下載到本地電腦妥善儲存(丟了伺服器可就沒法再登陸了),為安全,建議刪除伺服器端的私鑰。公鑰則可以任意公開。
2、使用以下命令將公鑰匯入到VPS:
cat /root/.ssh/id_rsa.pub >> /root/.ssh/authorized_keys
3、修改SSH的配置檔案/etc/ssh/sshd_config :
#RSAAuthentication yes #PubkeyAuthentication yes #AuthorizedKeysFile .ssh/authorized_keys
去掉上面3行前面的#,儲存後重啟SSH服務。
service sshd restart
至此你的linux伺服器已經支援使用SSH私鑰證書登入。在你使用SSH Key登入驗證成功後,還是為了安全,建議你關閉root使用者使用密碼登陸,關閉的方法如下:
修改SSH的配置檔案/etc/ssh/sshd_config,找到下面1行:
PasswordAuthentication yes
修改為:
PasswordAuthentication no
儲存後重啟SSH服務。
service sshd restart
好了,至此只要你儲存好你的私鑰(為安全,建議刪除伺服器端的私鑰),你的伺服器相比原來使用root使用者加密碼登陸來說