提供一個可直接部署的 Shell 腳本,清空主流 Linux 發行版常見系統與服務日誌,適用於審計前清理或磁碟空間緊急釋放。
clean_logs.sh#!/bin/bash
# 清空常見系統日誌
# 需 root 權限執行
LOG_FILES=(
"/var/log/syslog"
"/var/log/messages"
"/var/log/wtmp"
"/var/log/btmp"
"/var/log/maillog"
"/var/log/secure"
"/var/log/cron"
"/var/log/maillog"
"/var/log/openwebmail.log"
"/var/log/httpd/error_log"
"/var/log/httpd/access_log"
"/var/log/httpd/ssl_error_log"
"/var/log/httpd/ssl_request_log"
"/var/log/httpd/ssl_access_log"
"/var/log/nginx/error.log"
"/var/log/nginx/access.log"
)
for log in "${LOG_FILES[@]}"; do
if [[ -f "$log" ]]; then
: > "$log" # 等同 cat /dev/null > "$log",更高效
echo "Cleared: $log"
fi
done
# 重新載入 systemd-journald(如使用 journalctl)
systemctl reload systemd-journald 2>/dev/null || true
echo "所有日誌清理完成。"
chmod +x clean_logs.sh
sudo ./clean_logs.sh
而非手動清空,建議配置 /etc/logrotate.d/ 實現自動壓縮、保留天數、郵件通知:
/var/log/nginx/*.log {
daily
missingok
rotate 14
compress
delaycompress
notifempty
create 0640 www-data adm
sharedscripts
postrotate
[ -f /var/run/nginx.pid ] && kill -USR1 `cat /var/run/nginx.pid`
endscript
}
wtmp/btmp 會導致 last/lastb 無紀錄。