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

Linux chmod 命令失去執行權限?教你 7 招快速恢復執行屬性

編輯:Linux 教學

在 Unix/Linux 系統管理中,chmod 是調整檔案權限的核心指令。但若不慎將 /bin/chmod 自身的執行位元(x 屬性)移除,系統將陷入「無法修改權限」的死循環。本文整理 7 種實戰可行的恢復方案,涵蓋套件重裝、腳本語言呼叫、二進制替換、封存工具技巧等,助你快速奪回控制權。

方案一:透過套件管理器重新安裝 coreutils

最標準的做法是重新安裝提供 chmod 的套件。以 Debian/Ubuntu 為例:

sudo apt-get install --reinstall coreutils

RHEL/CentOS/Fedora 則使用:

sudo yum reinstall coreutils
# 或
sudo dnf reinstall coreutils

此法會將 /bin/chmod 還原為原廠預設權限(通常為 755),適用於根分區可寫、套件管理器正常運作的情境。

方案二:以直譯語言直接呼叫 chmod 系統呼叫

多數腳本語言內建 chmod() 包裝函式,可繞過 Shell 對執行位元的檢查。

  • Perl:perl -e 'chmod 0755, "/bin/chmod"'
  • Python:python -c "import os; os.chmod('/bin/chmod', 0o755)"
  • Node.js:require("fs").chmodSync("/bin/chmod", 0o755)
  • Ruby:ruby -e "File.chmod(0755, '/bin/chmod')"

只要該直譯器本身擁有執行權限(通常預設即有),即可生效。

方案三:編譯最小 C 程式替換 chmod

若系統仍保留 C 編譯器(gcc、cc 或 clang),可現場編譯一個僅呼叫 chmod() 的小程式:

cat > fix_chmod.c <<'EOF'
#include 
int main(void) { return chmod("/bin/chmod", 0755); }
EOF
gcc -o fix_chmod fix_chmod.c && ./fix_chmod

編譯產出的 fix_chmod 擁有執行位元,執行後即完成修復。

方案四:利用現有可執行檔「借殼」執行

Linux 核心允許將任意二進位資料寫入已具備執行位元的檔案(如 a.out、true、bash),再執行該檔案即可達到效果:

# 方法 A:覆寫 a.out
cat /bin/chmod > a.out
./a.out 0755 /bin/chmod

# 方法 B:借用 true
cp /bin/true /tmp/new_chmod
cat /bin/chmod > /tmp/new_chmod
/tmp/new_chmod 0755 /bin/chmod

原理是 execve() 僅檢查 inode 的執行位元,不驗證檔案內容是否為原始程式碼。

方案五:以 GNU tar / cpio 保留權限屬性解包

封存工具支援在建立/解壓時指定檔案模式:

# tar 指定模式建立並解壓
tar --mode=0755 -cf - /bin/chmod | tar -xvf -

# cpio 搭配 Perl 修改 header 權限位
echo chmod | cpio -o | perl -pe 's/^(.{21}).../${1}755/' | cpio -i -u

此法在單用戶模式或救援模式下同樣有效。

方案六:動態連結器直接載入 chmod 二進位

Linux 動態連結器(ld-linux.so*)本身具備執行位元,可直接載入任意 ELF 執行檔:

/lib64/ld-linux-x86-64.so.2 /bin/chmod 0755 /bin/chmod
# 或 32 位元系統
/lib/ld-linux.so.2 /bin/chmod 0755 /bin/chmod

亦可寫入 alias chmod='/lib64/ld-linux-x86-64.so.2 /bin/chmod' 暫時繞過。

方案七:使用 install 指令複製並設定權限

install 內建 -m 參數可於複製時指定模式,屬 GNU coreutils 一部分,通常未被波及:

install -m 755 /bin/chmod /tmp/chmod && mv /tmp/chmod /bin/chmod

此為最簡潔、相依性最低的方案之一。

補充:事前預防與事後驗證

  • 建立 chattr +i /bin/chmod 防止誤刪執行位元(需 root 解鎖)。
  • 修復後執行 ls -l /bin/chmod 確認輸出為 -rwxr-xr-x。
  • 若 /usr/bin/chmod 為獨立副本,同樣檢查並修復。

掌握上述技巧,下次遇到 chmod: cannot access '/bin/chmod': Permission denied 時,即可從容化解,避免重灌系統的麻煩。

Copyright © Windows教程網 All Rights Reserved