在Linux中禁用或啟用SSH根登錄並限制SSH訪問

每個人都知道,Linux 系統附帶 root 使用者訪問權限,而且預設情況下,外界可以啟用 root 存取。

出於安全考慮,讓未經授權的使用者啟用 ssh root 存取並不是個好主意。因為任何駭客都可以嘗試暴力破解您的密碼並存取您的系統。

Disable SSH Root Login

因此,最好擁有另一個您定期使用的帳戶,然後在必要時使用 ‘su -‘ 命令切換到 root 使用者。在開始之前,請確保您擁有一個常規使用者帳戶,並且您可以使用 su 或 sudo 來獲得 root 存取權限。

[ 您也可能會喜歡: 如何保護和加固 OpenSSH 伺服器 ]

在 Linux 中,很容易創建一個單獨的帳戶,以 root 使用者身份登錄,並簡單地運行 adduser 命令來創建一個獨立的使用者。一旦使用者被創建,只需按照下面的步驟來禁用通過 SSH 的 root 登錄。

我們使用 sshd 主配置文件來禁用 root 登錄,這將可以減少並防止 駭客 從獲得對您的 Linux 系統的 root 訪問。我們還會看到如何再次啟用 root 訪問,以及如何根據 用戶 列表限制 ssh 訪問。

禁用 SSH Root 登錄

要禁用 root 登錄,打開主 ssh 配置文件 /etc/ssh/sshd_config 以您選擇的編輯器。

# vi /etc/ssh/sshd_config

在文件中查找以下行。

#PermitRootLogin no

從該行的開頭刪除“#”。使該行看起來類似於此。

PermitRootLogin no
Disable Root Login in Linux

接下來,我們需要重新啟動 SSH 守護程序服務。

# systemctl restart sshd
OR
# /etc/init.d/sshd restart

現在嘗試使用 root 用戶登錄,您將收到“權限被拒絕”的錯誤。

$ ssh [email protected]
[email protected]'s password: 
Permission denied, please try again.
SSH Permission Denied Error

因此,從現在開始,請以普通用戶身份登錄,然後使用 ‘su’ 命令切換到 root 用戶。

$ ssh [email protected]
[email protected]'s password:
Last login: Mon Dec 27 15:04:58 2021 from 192.168.0.161

$ su -
Password:
Last login: Mon Dec 27 15:05:07 IST 2021 on pts/1
SSH User Login

啟用 SSH Root 登錄

要啟用 ssh root 登錄,打開文件 /etc/ssh/sshd_config

# vi /etc/ssh/sshd_config

查找以下行並刪除開頭的‘#’,然後保存文件。

PermitRootLogin yes
Enable Root Login in Linux

重新啟動 sshd 服務。

# systemctl restart sshd
OR
# /etc/init.d/sshd restart

現在嘗試使用 root 用戶登錄。

$ ssh [email protected]
[email protected]'s password:
Last login: Mon Dec 27 15:14:54 2021 from 192.168.0.161
SSH Root Login

限制 SSH 用戶登錄

使用者帳戶若在系統上眾多,那麼限制遠端 SSH 存取僅對那些真正需要的使用者是有意義的。打開/etc/ssh/sshd_config 檔案

# vi /etc/ssh/sshd_config

在檔案底部新增一行AllowUsers,並以空格分隔列出使用者名單。例如,使用者tecmintsheena都有遠端 SSH 存取權限。

AllowUsers tecmint sheena
Limit SSH User Login

現在重新啟動ssh服務。

Source:
https://www.tecmint.com/disable-or-enable-ssh-root-login-and-limit-ssh-access-in-linux/