Windows XP Windows 7 Windows 2003 Windows Vista Windows 綜合教學 Linux 系統教學
Windows 10 Windows 8 Windows 2008 Windows NT Windows Server 電腦軟體教學
您现在的位置: Windows教程網 >> Windows教程 >  >> Linux 系統教學 >> Linux 教學

CentOS 新增 sudo 用戶標準流程:visudo 配置、權限臨時修改與驗證

編輯:Linux 教學

CentOS 預設未配置 sudo,需手動編輯 /etc/sudoers 授權普通用戶執行管理指令。本文說明標準流程:切換 root、修改檔案權限、編輯配置、恢復權限、驗證生效。

操作步驟

  1. 切換 root:
    su - root
  2. 修改 sudoers 權限為可寫 (預設 0440 唯讀):
    chmod 0640 /etc/sudoers
  3. 編輯配置:
    vim /etc/sudoers
    # 找到
    root    ALL=(ALL)       ALL
    # 下方新增 (替換 username 為實際用戶名)
    username    ALL=(ALL)       ALL
    # 存檔退出
  4. 恢復唯讀權限 (關鍵,否則 sudo 拒絕執行):
    chmod 0440 /etc/sudoers
  5. 驗證:
    su - username
    sudo -l                    # 列出權限
    sudo systemctl status sshd # 測試執行

最佳實踐:使用 visudo 替代手動修改權限

visudo
# 直接在編輯器中新增行,存檔自動語法檢查與權限恢復,無需手動 chmod

強烈建議:生產環境務必用 visudo,防止語法錯誤導致無法 sudo 鎖死系統。

進階配置範例

# 僅允許特定指令免密
username  ALL=(ALL) NOPASSWD: /usr/bin/systemctl restart httpd

# 群組授權 (wheel)
%wheel    ALL=(ALL)       ALL
# 加入群組
usermod -aG wheel username

常見錯誤排查

  • sudo: /etc/sudoers is mode 0640, should be 0440:權限未恢復,執行 chmod 0440 /etc/sudoers。
  • sudo: parse error in /etc/sudoers near line X:語法錯誤,需進單用戶模式或 LiveCD 掛載修復。
  • 用戶不在 sudoers 中:檢查用戶名拼寫、群組成員關係 groups username。
Copyright © Windows教程網 All Rights Reserved