萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 伺服器教學

Linux 遞迴生成目錄檔案 MD5 雜湊值:find+xargs 一行指令與 PHP 腳本對比

需求場景

對目錄樹所有檔案產生 MD5 清單,用於完整性驗證、異地備份比對、變更偵測。

方法一:find + xargs + md5sum (一行指令,最高效)


# 標準寫法 (處理檔名含空白/特殊字元)
find /data/www/bbs/source -type f -print0 | xargs -0 md5sum > filelist.md5

# 解析:
# -type f        只處理一般檔案
# -print0        以 NUL (\0) 分隔輸出,安全處理特殊檔名
# xargs -0       讀取 NUL 分隔輸入
# md5sum         計算雜湊,輸出「雜湊值  兩個空格  檔案路徑」

方法二:PHP 腳本實現 (跨平台、可嵌入應用)



驗證雜湊清單


# 完整驗證 (顯示所有結果)
md5sum -c filelist.md5

# 僅顯示失敗項
md5sum -c filelist.md5 | grep FAILED

# 靜默模式 (腳本判斷用)
md5sum -c --status filelist.md5
if [ $? -ne 0 ]; then
    echo "發現檔案異動!"
    md5sum -c filelist.md5 | grep FAILED
fi

# 統計摘要
md5sum -c filelist.md5 2>&1 | tail -1
# md5sum: WARNING: 2 of 1147 computed checksums did NOT match

效能對比 (10 萬檔案測試環境)

方法耗時CPU 佔用記憶體適用場景
find + xargs -P8 md5sum45s高 (並行)低生產環境、大量檔案、Linux/Unix
find -exec md5sum {} +52s中低無 xargs -0 支援環境
PHP 腳本 (單執行緒)320s低中Windows、嵌入應用、需自訂邏輯
Python hashlib + multiprocessing50s高中跨平台、需複雜過濾/轉換

進階:並行加速版 (多核心利用)


# GNU parallel (最簡潔)
find /data -type f -print0 | parallel -0 -j$(nproc) md5sum > filelist.md5

# xargs 並行 (需 md5sum 支援並行輸出排序,GNU md5sum 通常安全)
find /data -type f -print0 | xargs -0 -P$(nproc) -n1 md5sum > filelist.md5

# 排序輸出以利比對 (find 順序不固定)
find /data -type f -print0 | xargs -0 md5sum | sort -k2 > filelist.md5

排除特定檔案/目錄


# 排除 .git、node_modules、*.log、tmp/
find /data -type f \
  -not -path "*/.git/*" \
  -not -path "*/node_modules/*" \
  -not -name "*.log" \
  -not -path "*/tmp/*" \
  -print0 | xargs -0 md5sum > filelist.md5

安全性提升:SHA-256 替代 MD5


# 同樣語法,改用 sha256sum
find /data -type f -print0 | xargs -0 sha256sum > filelist.sha256
sha256sum -c filelist.sha256

建議: 新專案直接用 SHA-256,避免 MD5 碰撞風險;舊系統相容可雙雜湊並存。

copyright © 萬盛學電腦網 all rights reserved