top、ps 等)與敏感配置檔(/etc/passwd 等)。md5sum 計算檔案指紋,與基線比對。#!/bin/bash
# file_monitor.sh - 關鍵檔案完整性監控
# 需配置郵件發送環境(postfix/sendmail/mailx)
EMAIL_TO="admin@example.com"
EMAIL_FROM="monitor@$(hostname -f)"
STAT_DIR="/var/lib/file_monitor"
CMD_LIST="/etc/file_monitor_cmds.txt" # 每行一個命令名,如 top ps netstat
SYS_LIST="/etc/file_monitor_files.txt" # 每行一個絕對路徑,如 /etc/passwd
mkdir -p "$STAT_DIR"
chmod 700 "$STAT_DIR"
# 取得本機主 IP(排除 127.x 與 Docker 虛擬網卡)
get_ip() {
ip -o -4 addr show scope global | awk '{print $4}' | cut -d/ -f1 | head -1
}
# 發送告警郵件
alert() {
local subject="$1"
local body="$2"
printf "%s\n" "$body" | mail -s "$subject" -r "$EMAIL_FROM" "$EMAIL_TO"
}
# 初始化基線
init_baseline() {
local baseline="$STAT_DIR/baseline.md5"
> "$baseline"
# 命令類
while read -r cmd; do
[[ -z "$cmd" ]] && continue
path=$(command -v "$cmd" 2>/dev/null) || continue
md5sum "$path" >> "$baseline"
done < "$CMD_LIST"
# 系統檔案類
while read -r f; do
[[ -z "$f" || ! -f "$f" ]] && continue
md5sum "$f" >> "$baseline"
done < "$SYS_LIST"
chmod 600 "$baseline"
}
# 檢查單個檔案
check_file() {
local file="$1"
local baseline="$STAT_DIR/baseline.md5"
local new_sum=$(md5sum "$file" | awk '{print $1}')
local old_line=$(grep " $file$" "$baseline" 2>/dev/null | head -1)
if [[ -z "$old_line" ]]; then
# 新增檔案,記錄基線
echo "$new_sum $file" >> "$baseline"
return
fi
local old_sum=$(echo "$old_line" | awk '{print $1}')
if [[ "$new_sum" != "$old_sum" ]]; then
local ip=$(get_ip)
alert "ALERT: $file modified on $ip" \
"Server IP: $ip
File: $file
Old MD5: $old_sum
New MD5: $new_sum
Time: $(date)
Please investigate immediately."
# 更新基線防止重複告警
sed -i "s|$old_sum $file|$new_sum $file|" "$baseline"
fi
}
# 主循環
init_baseline
while true; do
while read -r cmd; do
[[ -z "$cmd" ]] && continue
path=$(command -v "$cmd" 2>/dev/null) && check_file "$path"
done < "$CMD_LIST"
while read -r f; do
[[ -z "$f" ]] && continue
[[ -f "$f" ]] && check_file "$f"
done < "$SYS_LIST"
sleep 20
done
cat > /etc/file_monitor_cmds.txt <<'EOF'
top
ps
netstat
ss
lsof
EOF
cat > /etc/file_monitor_files.txt <<'EOF'
/etc/passwd
/etc/shadow
/etc/group
/etc/gshadow
/etc/sudoers
/etc/ssh/sshd_config
/bin/bash
/usr/bin/sudo
EOF
/etc/rc.local)。mail 命令可用(安裝 mailx + postfix)。inotifywait(inotify-tools)實現事件驅動,替代輪詢,降低延遲與 CPU 佔用。auditd 審計子系統,獲得更豐富的上下文(進程、用戶、調用鏈)。sha256sum 或 gpg --clearsign 防篡改。這支腳本提供了一個輕量、零依賴的檔案完整性監控基線。生產環境建議結合 inotify+auditd+集中式日誌平台(ELK/Splunk)構建纵深防禦體系。