In high-throughput network environments, edge firewalls generate massive volumes of NetFlow data. These logs are critical for security analysis, capacity planning, and forensic investigations. However, storing uncompressed, raw log files indefinitely consumes disk space rapidly and degrades system performance. The standard industry practice is to implement an automated rotation strategy that archives old logs and compresses them efficiently. This guide details how to construct a robust Bash cron job to manage high-volume NetFlow logs on a Linux-based edge firewall or management server.
Understanding the Architecture and Prerequisites
Before writing automation scripts, it is essential to understand the environment. In this lab scenario, we assume a standard Linux distribution (such as RHEL 8/9, Ubuntu 22.04 LTS, or Debian 11) running on an edge firewall or a dedicated log collector. The system utilizes rsyslog or journalctl to ingest NetFlow data from the firewall’s sensor interface.
Prerequisites for this lab:
* Root Access: You must have sudo privileges to manage cron jobs and write to /var/log.
* Disk Space: Ensure the partition hosting logs has at least 50% free space to handle temporary compression files before deletion.
* Compression Tool: Verify that gzip is installed (standard on most Linux distros). For higher performance with large files, pigz (parallel gzip) is often preferred but requires manual installation.
* Cron Daemon: Ensure the cron service is active (systemctl status cron or crond).
Designing the Rotation Logic and Script Structure
A naive approach to log rotation is simply deleting old files. This is dangerous because it destroys forensic evidence before analysis. The correct pattern involves moving files to an archive directory, compressing them, and then removing the original uncompressed file only after successful compression.
We will create a script located at /usr/local/bin/rotate_netflow.sh. This location is outside standard system paths, ensuring the script persists across OS updates.
The script logic follows these steps:
1. Identify Target Files: Locate log files older than a specific retention period (e.g., 7 days).
2. Move to Archive: Transfer uncompressed logs to an archive directory (e.g., /var/log/netflow/archive/).
3. Compress: Apply gzip compression to reduce storage footprint by roughly 80-90%.
4. Cleanup: Remove the original uncompressed file from the active log directory.
5. Error Handling: Log any failures to a separate error file for monitoring.
#!/bin/bash
# Script: /usr/local/bin/rotate_netflow.sh
# Function: Rotate and compress NetFlow logs older than 7 days
set -e # Exit immediately if a command exits with a non-zero status
LOG_DIR="/var/log/netflow"
ARCHIVE_DIR="${LOG_DIR}/archive"
RETENTION_DAYS=7
ERROR_LOG="${LOG_DIR}/rotation_errors.log"
# Ensure archive directory exists
mkdir -p "$ARCHIVE_DIR"
# Find files older than N days in the log directory
# Using find with -mtime ensures we only target old files safely
find "$LOG_DIR" -name "*.netflow" -type f -mtime +${RETENTION_DAYS} | while read file; do
# Skip if it is already a compressed file (e.g., .gz)
if [[ $file == *.gz ]]; then
continue
fi
echo "Rotating: $file" >> "$ERROR_LOG"
# Move to archive directory first
mv "$file" "$ARCHIVE_DIR/"
# Compress the file in place.
# Note: On some systems, gzip modifies the filename to add .gz automatically.
# If using pigz, ensure it is called explicitly. Here we use standard gzip.
gunzip -k "$ARCHIVE_DIR/$(basename $file)" || true
# Remove the original uncompressed file from the source directory
rm -f "$file"
echo "Successfully processed: $file" >> "$ERROR_LOG"
done
Configuring the Cron Job for Scheduled Execution
Once the script is created and made executable (chmod +x /usr/local/bin/rotate_netflow.sh), it must be scheduled via cron. The goal is to run this task during a low-traffic window, typically early in the morning (e.g., 04:30 AM) or every 6 hours for extremely high-volume environments.
Edit the crontab file using crontab -e. Add the following line:
# Run NetFlow rotation at 4:30 AM every day
30 4 * * * /usr/local/bin/rotate_netflow.sh >> /var/log/netflow/cron_rotation.log 2>&1
Explanation of the Cron Syntax:
* 30 4: Execute at minute 30, hour 4.
* * * *: Run every day of the week and month.
* /usr/local/bin/rotate_netflow.sh: The full path to the script is required; relative paths often fail due to different environment variables in cron contexts.
* >> /var/log/netflow/cron_rotation.log 2>&1: Redirects both standard output and errors to a log file for auditing.
Expected Results and Verification Steps
After the cron job executes, verification is critical to ensure the automation is functioning as intended.
Expected File System State:
* The /var/log/netflow/ directory should contain only recent logs (less than 7 days old) and potentially some compressed archives if the retention policy allows keeping .gz files in place of originals for a short period.
* The /var/log/netflow/archive/ directory should contain compressed files with names like firewall_netflow_2023-10-25.gz.
* Disk usage on the log partition should stabilize, showing a gradual decrease as old data is archived and compressed.
Verification Commands:
To verify the job ran successfully, check the cron output log:
tail -n 50 /var/log/netflow/cron_rotation.log
Look for entries indicating “Successfully processed”. If you see errors, check the rotation_errors.log inside the netflow directory.
You can also manually trigger the script to test it immediately:
sudo /usr/local/bin/rotate_netflow.sh
ls -lh /var/log/netflow/archive/
Common Errors and Troubleshooting
Several issues frequently arise when implementing log rotation in production environments.
1. “Permission Denied” Errors:
The script runs under the root user via cron, but if the log files are owned by a specific application user (e.g., firewall-agent) with restrictive permissions, the script may fail to move them.
* Fix: Ensure the log directory permissions allow root to read and write, or configure the application to drop privileges appropriately.
2. Disk Full During Compression:
Compressing a 50GB log file creates a temporary state where both the original and the compressed version exist momentarily. If disk space is tight, this can fill the partition before the original is deleted.
* Fix: Use gunzip -k carefully or ensure the archive directory resides on a different mount point with ample space. Alternatively, use tools like logrotate which handle temporary file management more gracefully.
3. Race Conditions:
If multiple cron jobs attempt to rotate logs simultaneously (e.g., if you schedule hourly jobs), they might race against each other.
* Fix: Use a lock file mechanism within the script (flock) to ensure only one instance runs at a time.
Student Practice Task and Industry Application
Student Practice Task:
In your virtual lab environment, create 10 dummy log files in /var/log/netflow/ named netflow_day_1.txt through netflow_day_10.txt. Modify the dates of the first five files to be 8 days in the past using touch -d "8 days ago" filename. Run your cron job manually and verify that only the old five files are moved to the archive directory and compressed.
Industry Application:
In a professional setting, this automation feeds into a larger workflow. The compressed archives are often ingested by a SIEM (Security Information and Event Management) system like Splunk or Elastic Stack for long-term retention compliance (e.g., GDPR or HIPAA requirements). The cron job ensures that the local edge device does not become a bottleneck while upstream systems receive data at a sustainable rate.
Conclusion
Automating NetFlow log rotation is a fundamental skill for network engineers and DevOps practitioners. By implementing a Bash script within a cron schedule, you ensure that high-volume logs are managed efficiently without manual intervention. This approach balances the need for immediate access to recent traffic data with the necessity of long-term archival for security auditing. Always test these scripts in a safe lab environment before deploying them to production edge firewalls, ensuring your automation enhances rather than disrupts network operations.
Educational-use notice: This tutorial is for learning and controlled lab use only. Test carefully, use backups, and obtain authorization before making changes. Do not run unfamiliar commands on production systems. We accept no responsibility for misuse, damage, data loss, or production issues.

