Network traffic analysis is a cornerstone of modern IT operations, yet manual log inspection is unsustainable for large-scale environments. Automating the parsing of NetFlow logs allows security analysts and network engineers to identify bandwidth hogs, detect anomalies, and troubleshoot connectivity issues without constant human intervention. This guide walks you through building a robust Bash script on a Linux system that ingests raw NetFlow data, aggregates traffic statistics by hour, and emails a formatted report to designated stakeholders.
This lab is designed for IT students and junior engineers looking to master workflow automation using standard open-source tools. It integrates concepts of text processing with awk and grep, scheduling via cron, and secure email transmission using mailx or sendmail. By the end of this exercise, you will have a deployable solution that transforms raw binary or text-based flow data into actionable intelligence.
Understanding NetFlow Log Formats and Prerequisites
Before writing any code, it is crucial to understand the input format. While Cisco devices often export NetFlow v5 or v9 in proprietary formats, many open-source routers (like pfSense or various Linux distributions with ntopng) export logs in standard text formats compatible with Unix tools. For this lab, we assume a simplified text-based log where each line represents a flow record containing source IP, destination IP, protocol, and bytes transferred.
Prerequisites:
* A Linux distribution (Ubuntu, Debian, CentOS, or RHEL).
* Basic familiarity with the terminal and command-line interface.
* Root or sudo access to install dependencies like mailx or configure SMTP credentials.
* A sample NetFlow log file (we will generate a synthetic one for testing).
Note on Security: Never run this script directly against production logs without validating that the source IP addresses and byte counts match your expected baseline. Always test email delivery in a sandbox environment first to avoid accidental notifications during development.
Step-by-Step Script Construction
We will create a file named netflow_analyzer.sh. This script will read from an input log file, calculate total bytes per hour, and format the output for email.
-
Define Variables and Paths: Start by setting the paths to your log file, the output report file, and the recipient email address.
“`bash
#!/bin/bashConfiguration variables
LOG_FILE=”/var/log/netflow/sample_flows.log”
REPORT_FILE=”/tmp/hourly_traffic_report_$(date +%Y%m%d_%H%M%S).txt”
RECIPIENT_EMAIL=”admin@company.local”
SMTP_SERVER=”smtp.company.local”
FROM_EMAIL=”network-monitor@company.local”Validate input file exists
if [ ! -f “$LOG_FILE” ]; then
echo “Error: Log file $LOG_FILE not found.” | tee -a /var/log/netflow_errors.log
exit 1
fi
“` -
Parse and Aggregate Data: Use
awkto iterate through the log file. We assume a space-separated format where the last column represents bytes transferred. The script groups these by the hour extracted from a timestamp field (assumed to be the second column).
“`bash
# Create header for the report
{
echo “=== Hourly NetFlow Traffic Report ===”
echo “Generated: $(date)”
echo “Source Log: $LOG_FILE”
echo “”
echo “Hour | Total Bytes Transferred | Flow Count”
echo “—–|————————-|————”
} > “$REPORT_FILE”Parse the log using AWK
Assuming format: Timestamp SourceIP DestIP Protocol Bytes …
awk ‘{
# Extract hour from timestamp (adjust index based on your actual log format)
split($1, datetime, “:”)
hour = datetime[2]
bytes = $NF # Assume last field is byteskey = hour "_" $2 "_" $3 # Group by Hour + SrcIP + DstIP for detail, or just hour for summary total_bytes[key] += bytes flow_count[key]++}
END {
# Sort and print results
n = asorti(total_bytes, sorted_keys)
for (i=1; i<=n; i++) {
split(sorted_keys[i], parts, “_”)
hour = parts[1]
src = parts[2]
dst = parts[3]
printf “%s | %d | %d\n”, hour, total_bytes[sorted_keys[i]], flow_count[sorted_keys[i]]
}
}’ “$LOG_FILE” >> “$REPORT_FILE”
“` -
Generate Email Content and Send: Append a footer to the report and pipe it into
mailx. Ensuremailxis configured with your SMTP server details. Ifmailxis unavailable, you may need to install it (apt install mailutils) or usemutt/sendmail.
“`bash
{
echo “”
echo “=== End of Report ===”
echo “Total Flows Analyzed: $(awk ‘END{print NR}’ “$LOG_FILE”)”
} >> “$REPORT_FILE”Send email (requires mailx configured with -s subject and smtp options)
if command -v mailx &> /dev/null; then
mailx -s “NetFlow Traffic Report: $(date ‘+%Y-%m-%d %H:%M’)” \
“$RECIPIENT_EMAIL” < “$REPORT_FILE”
echo “Report successfully emailed to $RECIPIENT_EMAIL”
else
echo “Warning: mailx not found. Please configure SMTP or install mailutils.”
exit 1
fi
“`
Scheduling the Script with Cron
A script runs only when manually executed. To achieve true automation, we must schedule it using cron. This ensures hourly traffic reports are generated and sent automatically every hour.
- Edit Crontab: Run
crontab -eto open the user’s cron schedule. - Add the Job Entry: Add a line to run the script at the top of every hour (minute 0).
bash
# Run netflow analysis at the start of every hour
0 * * * * /usr/bin/bash /path/to/netflow_analyzer.sh >> /var/log/netflow_cron.log 2>&1 - Verification: After setting up, wait for the next hour to pass. Check
/var/log/netflow_cron.logand your inbox to verify delivery.
Common Errors and Troubleshooting
When deploying this automation in a real lab or workplace, several issues frequently arise:
- Permission Denied: If the script cannot read the log file or write to
/tmp, check file permissions (ls -l). Ensure the user running the cron job has read access to the logs and write access to the temp directory.- Fix:
chmod 644 /var/log/netflow/sample_flows.logandchown root:root /var/log/netflow_errors.log.
- Fix:
- Mail Delivery Failed: If the email fails, check if the SMTP server is reachable from the Linux host (
telnet smtp.company.local 25). Many cloud providers block direct port 25 access; use a relay like SendGrid or Postfix configured for your domain.- Fix: Configure
mailxwith explicit-vflags to see verbose output, and ensure SPF/DKIM records are set up on your DNS.
- Fix: Configure
- AWK Syntax Errors: If your NetFlow log format differs from the example (e.g., tab-separated instead of space-separated), the field indices in the
awkcommand will be wrong.- Fix: Use
head -1 /var/log/netflow/sample_flows.log | cat -Ato visualize invisible characters and adjust the$NFor specific column references accordingly.
- Fix: Use
Student Practice Task and Industry Application
Student Practice Task:
Modify the script above to filter traffic only for a specific subnet (e.g., 192.168.10.0/24). Update the awk logic to ignore lines where the source IP does not start with 192.168.10. Add a conditional check: if total bytes exceed 1 GB, append a warning message “HIGH TRAFFIC ALERT” to the email body before sending.
Industry Application:
In a production environment, this script forms part of a larger SIEM (Security Information and Event Management) ingestion pipeline. The hourly report can be ingested by a dashboarding tool like Grafana or Kibana. Instead of emailing raw text, you might modify the output to generate a JSON file that your monitoring stack parses to update live charts. Furthermore, integrating this with Ansible allows you to push updated parsing logic across hundreds of edge routers simultaneously, ensuring consistent log analysis policies organization-wide.
Conclusion
Automating NetFlow log analysis transforms network operations from reactive troubleshooting to proactive monitoring. By leveraging Bash scripting, awk for data aggregation, and cron for scheduling, even junior engineers can build powerful monitoring tools without expensive commercial software. Remember that while this lab provides a functional template, real-world deployment requires careful attention to security, permission management, and SMTP configuration. Always validate your scripts in an isolated lab environment before applying them to production network logs.
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.

