[Linux] 如何禁止使用口令只允許使用密鑰建立 SSH 連接


1. 創建 SSH KEY

 

  使用 ssh-keygen 生成一個密鑰對,並且將公鑰注冊到服務器的 $HOME/.ssh/authorized_keys 文件。

 

2. 確保啟用 SSH 公鑰認證功能

 

  查看 /etc/ssh/sshd_config 文件,確保以下兩條為 yes:

RSAAuthentication yes
PubkeyAuthentication yes

 

  一般它們默認都是 yes,如果不是,請修改為 yes,保存並且重啟 SSH 服務:

$ sudo service ssh reload

 

3. 禁止密碼安全驗證

 

  編輯 /etc/ssh/sshd_config 文件,確保以下內容出現在文件中:

ChallengeResponseAuthentication no
PasswordAuthentication no
UsePAM no

 

  保存並重啟 SSH 服務:

$ sudo service ssh restart

 

  如果你當前處於 SSH 連接登錄狀態,可能重啟服務會失敗,可以嘗試重啟系統。

 

4. 禁止特定條件使用密碼登錄

 

  有時我們並不想禁止所有用戶的口令登錄,可以通過配置 sshd_config 文件來實現對特定對象的登錄設置。

 

  使用 $ man sshd_config 查看幫助信息。sshd_config 支持在文件中增加 Match 區塊,如果 Match 關鍵字所在行的條件匹配成功,則 Match 后所有的關鍵字將被逐個加載,直到遇見另一個 Match 關鍵字或者文件結尾。所以一般 Match 區塊添加在 sshd_config 文件末尾。

 

  Match 關鍵字支持的條件包括 User, Group, Host 和 Address,條件樣式是單個字符串,多個樣式使用逗號分隔,也可以使用通配符(*)和求反符號(!)。

 

  Address 條件樣式可以是 CIDR(地址/掩碼)格式,例如:192.0.2.0/24 或 3ffe:ffff::/32。

 

  例如禁止用戶 foo,用戶組 bar 使用口令登錄,在 /etc/ssh/sshd_config 文件末尾添加以下內容:

Match User foo, Group bar
    PasswordAuthentication no

 

  禁止除用戶 foo 以外其他用戶使用口令登錄:

Match User *, !foo
    PasswordAuthentication no

 

  Match 區塊支持的關鍵字包括:

AllowAgentForwarding, AllowTcpForwarding, AuthorizedKeysFile, AuthorizedPrincipalsFile, Banner, ChrootDirectory, ForceCommand, GatewayPorts, GSSAPIAuthentication, HostbasedAuthentication, HostbasedUsesNameFromPacketOnly, KbdInteractiveAuthentication, KerberosAuthentication, MaxAuthTries, MaxSessions, PasswordAuthentication, PermitEmptyPasswords, PermitOpen,  PermitRootLogin, PermitTunnel, PubkeyAuthentication, RhostsRSAAuthentication, RSAAuthentication, X11DisplayOffset, X11Forwarding, X11UseLocalHost.

  

  sshd_config 文件內容大小寫敏感,編輯該文件一定要小心仔細,如有不慎可能導致 SSH 服務器無法啟動。如果你的主機就在你身邊,你也許還可以從歡迎界面登錄來修復錯誤,如果你只能通過 SSH 遠程登錄主機,Wooo~ 那就只能祝你好運了。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM