#!/bin/bash # ============================================================ # File Integrity Monitor for ruihanzx.com # Usage: # sudo ./thinkphp-integrity.sh snapshot # 建立基线 # sudo ./thinkphp-integrity.sh check # 比对检查 # # 部署: /usr/local/bin/thinkphp-integrity.sh # cron: 0 3 * * * /usr/local/bin/thinkphp-integrity.sh check # ============================================================ SNAPSHOT="/var/secure/thinkphp-checksum.txt" CURRENT="/tmp/thinkphp-checksum-$$.txt" FLAGFILE="/var/run/thinkphp-integrity.flag" PROJECT="这里填写你的项目绝对路径" take_snapshot() { mkdir -p /var/secure find "$PROJECT" -type f \( -name "*.php" -o -name "*.html" -o -name "*.js" -o -name "*.css" \) \ ! -path "*/runtime/*" \ ! -path "*/uploads/*" \ ! -path "*/.git/*" \ ! -path "*/.codegraph/*" \ ! -path "*/node_modules/*" \ -exec md5sum {} \; | sort -k2 > "$SNAPSHOT" echo "基线已建立:$(wc -l < "$SNAPSHOT") 个文件" } do_check() { if [ ! -f "$SNAPSHOT" ]; then echo "错误:基线文件 $SNAPSHOT 不存在,请先执行 snapshot" exit 1 fi find "$PROJECT" -type f \( -name "*.php" -o -name "*.html" -o -name "*.js" -o -name "*.css" \) \ ! -path "*/runtime/*" \ ! -path "*/uploads/*" \ ! -path "*/.git/*" \ ! -path "*/.codegraph/*" \ ! -path "*/node_modules/*" \ -exec md5sum {} \; | sort -k2 > "$CURRENT" # diff: < 基线独有(缺失),> 当前独有(新增或篡改) diff "$SNAPSHOT" "$CURRENT" | grep '^[<>]' | \ sed "s/^/[变更] /" | \ awk '{print $1, $NF}' > "$FLAGFILE" rm -f "$CURRENT" if [ -s "$FLAGFILE" ]; then echo "警告:$(wc -l < "$FLAGFILE") 个文件发生变化!" cat "$FLAGFILE" | while read line; do echo " $line" done else echo "所有文件正常" rm -f "$FLAGFILE" fi } show_help() { echo "用法: $0 {snapshot|check}" echo "" echo " snapshot 建立/更新文件校验基线" echo " check 对比当前文件,报告差异" } case "${1:-help}" in snapshot) take_snapshot ;; check) do_check ;; help|--help|-h) show_help ;; *) echo "未知命令: $1"; show_help; exit 1 ;; esac