Linux配置使用SSH Key登錄並禁用root密碼登錄

img

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用戶加密碼登陸來說已經安全多了。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章