Linux_SSH服務器只允許Key建立連接
1. 創(chuàng)建 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 文件胃碾,確保以下內(nèi)容出現(xiàn)在文件中:
ChallengeResponseAuthentication no
PasswordAuthentication no
UsePAM no
保存并重啟 SSH 服務:
$ sudo service ssh restart
如果你當前處于 SSH 連接登錄狀態(tài),可能重啟服務會失敗隔嫡,可以嘗試重啟系統(tǒng)甸怕。
4. 禁止特定條件使用密碼登錄
有時我們并不想禁止所有用戶的口令登錄,可以通過配置 sshd_config 文件來實現(xiàn)對特定對象的登錄設置腮恩。
使用 $ man sshd_config 查看幫助信息。sshd_config 支持在文件中增加 Match 區(qū)塊温兼,如果 Match 關(guān)鍵字所在行的條件匹配成功秸滴,則 Match 后所有的關(guān)鍵字將被逐個加載,直到遇見另一個 Match 關(guān)鍵字或者文件結(jié)尾募判。所以一般 Match 區(qū)塊添加在 sshd_config 文件末尾荡含。
Match 關(guān)鍵字支持的條件包括 User, Group, Host 和 Address,條件樣式是單個字符串届垫,多個樣式使用逗號分隔释液,也可以使用通配符(*)和求反符號(!)。
Address 條件樣式可以是 CIDR(地址/掩碼)格式装处,例如:192.0.2.0/24 或 3ffe:ffff::/32误债。
例如
禁止用戶 foo,用戶組 bar 使用口令登錄妄迁,在 /etc/ssh/sshd_config 文件末尾添加以下內(nèi)容:
Match User foo, Group bar
PasswordAuthentication no
禁止除用戶 foo 以外其他用戶使用口令登錄:
Match User *, !foo
PasswordAuthentication no
Match 區(qū)塊支持的關(guān)鍵字包括:
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.