Linux 建立限制指令的使用者

要建立一個限制極高的專用帳號,使其只能執行 smartctl -a,最安全且乾淨的做法是利用 Linux 的 SSH Command Restriction (Force Command) 機制,搭配 sudoers 最小權限設定。

以下是完整的設定步驟:

步驟 1:建立受限使用者

在目標 Linux 機器上建立一個專門用於監控的帳號(例如命名為 smartmon),並停用密碼登入:

# 建立使用者 smartmon,禁用密碼並停用標準 shell
sudo useradd -m -s /bin/bash smartmon

步驟 2:設定 sudoers 最小權限

smartctl 需要 root 權限才能存取硬碟底層控制介面。透過 visudo 允許 smartmon 只能免密碼執行 smartctl:

  1. 開啟 sudo 設定檔:

    sudo visudo -f /etc/sudoers.d/smartmon
    
  2. 寫入以下內容(嚴格限制只能帶 -a 參數,或對所有磁碟裝置放行):

    程式碼片段
    # 允許 smartmon 免密碼以 root 權限執行 smartctl -a
    smartmon ALL=(root) NOPASSWD: /usr/sbin/smartctl -a *
    smartmon ALL=(ALL) NOPASSWD: /usr/sbin/smartctl
    

步驟 3:設定 SSH Key 與強制指令 (Force Command)

這是最關鍵的一步。透過 SSH 公鑰中的 command= 限制,即使有人取得該公鑰,也絕對無法執行 SSH 互動 Shell 或任何其他指令。

  1. 建立 .ssh 目錄:

    sudo mkdir -p /home/smartmon/.ssh
    sudo chmod 700 /home/smartmon/.ssh
    
  2. 編輯 authorized_keys:

    sudo nano /home/smartmon/.ssh/authorized_keys
    
  3. 貼上你的公鑰,並在最前端加上限制參數: 在公鑰(例如 ssh-ed25519 AAAAC3N...)的最前面加上 command="..." 與安全防禦參數:

    command="sudo /usr/sbin/smartctl -a $SSH_ORIGINAL_COMMAND",no-port-forwarding,no-x11-forwarding,no-agent-forwarding,no-pty ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAI... (公鑰內容)
    

    說明:

    • command="...":強制 SSH 登入時自動套用 sudo smartctl,並傳遞傳進來的參數。

    • no-port-forwarding,no-x11-forwarding,no-agent-forwarding,no-pty:關閉所有 SSH 轉發功能與 PTY 虛擬終端,徹底切斷互動 Shell。

  4. 調整權限與擁有者:

    sudo chmod 600 /home/smartmon/.ssh/authorized_keys
    sudo chown -R smartmon:smartmon /home/smartmon/.ssh

測試驗證

完成後,在中控主機嘗試進行連線測試:

1. 正常抓取硬碟 S.M.A.R.T. 資料(應該成功)

ssh smartmon@<目標IP> /dev/sda

image.png


Revision #2
Created 29 October 2026 06:09:38 by Jason
Updated 29 October 2026 06:18:58 by Jason