Automation guides, explanations and reader checklists on whilenetworking.com

Bash Hands-On: Creating a Cron Job that Parses NetFlow Logs to Identify Top Talkers and Generate Daily Traffic Summaries

Network traffic analysis is critical for maintaining bandwidth efficiency and detecting anomalies. While commercial tools offer powerful dashboards,…

Network traffic analysis is critical for maintaining bandwidth efficiency and detecting anomalies. While commercial tools offer powerful dashboards, understanding how to parse raw data using open-source utilities like nfdump or ntopng combined with standard Unix text processing tools provides a robust, cost-effective baseline. This guide walks you through building an automated Bash script that ingests NetFlow logs, identifies the “top talkers” (hosts consuming the most bytes), and generates a daily summary report. We will then configure a cron job to run this analysis automatically every morning.

Prerequisites and Environment Setup

Before writing the script, ensure your environment meets specific requirements. This guide assumes a Linux distribution such as Ubuntu or Debian, which is common in server environments. You will need root or sudo privileges to install dependencies and set up the cron daemon.

Required Software:
* nfdump: A popular tool for parsing NetFlow logs exported by routers or firewalls (e.g., Cisco ASA, Juniper, Palo Alto).
* awk, sort, uniq: Standard GNU coreutils available on almost all systems.
* cron: The standard Unix scheduler.

Safety Note: Always test scripts in a lab environment or a non-production directory before deploying to production servers. Incorrect parsing logic can lead to skewed metrics, though it rarely causes system instability. Ensure your NetFlow collector has read permissions for the log files and write permissions for the output directory.

Step 1: Install Dependencies and Create Output Directories

First, install the necessary packet capture analyzer. On Ubuntu/Debian systems, use the package manager:

sudo apt-get update
sudo apt-get install nfdump -y

Next, create a dedicated directory for your analysis outputs to keep your system clean. We will create a folder named /var/log/traffic-analysis where daily reports will be stored. Ensure this directory exists and is writable by the user running the cron job (often root).

sudo mkdir -p /var/log/traffic-analysis
sudo chown root:adm /var/log/traffic-analysis

Step 2: Developing the Parsing Script

We will create a Bash script named analyze_traffic.sh. This script will read from a sample NetFlow database file (typically .pcap or plain text depending on the export format), calculate total bytes per IP address, and sort them.

Create the file using your preferred editor (e.g., nano or vim). Below is the logic for a standard nfdump output format:

#!/bin/bash
# File: analyze_traffic.sh
# Purpose: Parse NetFlow logs and identify top 10 talkers by bytes.

# Configuration variables
LOG_FILE="/var/log/nfdump/flow.db"      # Path to your parsed flow database
OUTPUT_DIR="/var/log/traffic-analysis"   # Directory for reports
REPORT_FILE="${OUTPUT_DIR}/top_talkers_$(date +%Y-%m-%d).txt" # Daily report path

# Check if log file exists
if [ ! -f "$LOG_FILE" ]; then
    echo "[ERROR] Log file not found: $LOG_FILE"
    exit 1
fi

# Create output directory if it doesn't exist
mkdir -p "$OUTPUT_DIR"

# Parse the flow database
# nfdump -r <file> -o ascii -f '%ip.src %bytes' extracts source IP and bytes.
# We pipe this to awk to sum bytes per IP, then sort numerically in reverse order.
nfdump -r "$LOG_FILE" -o ascii -f '%ip.src %bytes' 2>/dev/null | \
    awk '{
        ip = $1;
        bytes = $2;
        if (bytes != "" && ip != "") {
            total[ip] += bytes;
        }
    }
    END {
        for (ip in total) {
            print total[ip], ip;
        }
    }' | \
    sort -rn | \
    head -n 10 > "$REPORT_FILE"

# Check if the report was generated successfully
if [ $? -eq 0 ]; then
    echo "[SUCCESS] Report generated: $REPORT_FILE"
else
    echo "[ERROR] Failed to generate report."
    exit 1
fi

Explanation of Key Commands:
* nfdump -r ... -o ascii: Reads the database and converts it to ASCII text, filtering only source IP and byte count.
* awk '{...}': Iterates through lines, accumulating bytes for each IP address in an associative array (total[ip]).
* sort -rn: Sorts the output numerically in reverse order (highest bytes first).
* head -n 10: Limits the output to the top 10 consumers.

Expected Output:
When run manually, you should see a text file containing lines like:

15403200 192.168.1.50
12050000 10.0.0.15
8500000 172.16.0.4
...

Step 3: Configuring the Cron Job

To automate this process, we need to schedule the script to run daily at a specific time, such as 6:00 AM. Open the crontab editor for root or your user:

sudo crontab -e

Add the following line to execute the script every day at 6:00:

0 6 * * * /usr/local/bin/analyze_traffic.sh >> /var/log/traffic-analysis/cron.log 2>&1

Breakdown of the Cron Syntax:
* 0 6 * * *: Run at minute 0, hour 6, every day of the month, every month, every day of the week.
* /usr/local/bin/analyze_traffic.sh: The full path to your script (adjust if stored elsewhere).
* >> /var/log/.../cron.log 2>&1: Appends both standard output and errors to a log file for troubleshooting.

Step 4: Verification and Common Errors

After setting up the cron job, verify it is working. Check the status of the cron daemon:

systemctl status cron
# or on systemd systems
sudo systemctl status crond

Wait until after 6:00 AM (or run the command manually for immediate testing) and check the log file specified in the script to ensure no errors occurred.

Common Errors and Fixes:
* Permission Denied: If you see “Permission denied” when writing to the output file, ensure the cron job is running as a user with write access to /var/log/traffic-analysis. Often, cron jobs run as root, but directory ownership might be restricted. Use sudo chown root:adm on directories if needed.
* Log File Not Found: If nfdump cannot read the source file, check the path in the script variables. Ensure the NetFlow collector is still writing to that location.
* Missing Dependencies: If awk or nfdump commands fail, they may not be installed. Re-run the installation steps in Step 1.

Industry Application and Student Practice Task

Industry Scenario:
In a mid-sized enterprise, the Network Operations Center (NOC) uses this script as part of a tiered monitoring strategy. During business hours, commercial SIEM tools handle real-time alerts. However, during off-hours, this Bash-based cron job runs to provide leadership with a digestible summary of bandwidth hogs, helping them decide whether to implement Quality of Service (QoS) policies or investigate potential malware infections on high-volume hosts.

Student Practice Task:
1. Set up a virtual machine (e.g., using VirtualBox with Ubuntu Server).
2. Generate dummy NetFlow data using nfdump‘s test mode or a similar generator to create a sample .db file.
3. Modify the script above to filter for specific subnets (e.g., only analyze traffic from the 192.168.10.0/24 network).
4. Install crontab and schedule the modified script to run at a time convenient for your lab session.
5. Document any errors you encounter in a README file within your project directory.

By mastering these steps, you gain proficiency in workflow automation, log analysis, and system scheduling—skills highly valued in DevOps and Network Engineering roles. Always remember that while this script provides valuable insights, it should be complemented by broader network monitoring solutions for comprehensive security posture management.

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.