Automation guides, explanations and reader checklists on whilenetworking.com

Bash Challenge: Creating a Script to Automatically Archive Old Syslog Files to S3 While Flagging Critical Alerts in Real-Time

In modern DevOps and Site Reliability Engineering (SRE) environments, managing high-volume log data is a constant challenge. Syslog files can grow rapidly on…

In modern DevOps and Site Reliability Engineering (SRE) environments, managing high-volume log data is a constant challenge. Syslog files can grow rapidly on Linux servers, consuming disk space and making real-time analysis difficult if not managed correctly. A robust automation strategy involves archiving historical logs to durable object storage like Amazon S3 while simultaneously scanning for critical security alerts in near real-time. This guide walks you through building a Bash script that handles both tasks efficiently, integrating Python for advanced alert parsing where necessary.

Understanding the Architecture and Prerequisites

Before writing the script, it is essential to understand the components involved. The solution relies on standard Linux utilities like find, rsync or aws s3 cp for archiving, and regular expressions (regex) within Bash or Python for pattern matching. You will also need AWS credentials configured locally using the aws configure command or environment variables.

Prerequisites:
* A Linux environment with Bash 4.x or higher.
* The aws-cli installed and configured (aws --version).
* An S3 bucket created for log archival (e.g., company-logs-archive).
* Permissions to read from /var/log/syslog (or auth.log) and write to the S3 bucket.

Step-by-Step Script Construction

We will create a script named syslog_archiver.sh. This script performs two distinct functions: it identifies log files older than 7 days for archiving and scans recent logs for critical keywords like “CRITICAL”, “FATAL”, or specific IP addresses associated with brute-force attacks.

Step 1: Define Configuration Variables

Start by setting up your environment variables. This ensures the script is portable and easy to adjust without modifying the logic.

#!/bin/bash

# Configuration Variables
LOG_DIR="/var/log"
ARCHIVE_BUCKET="company-logs-archive"
DATE_SUFFIX=$(date +%Y-%m-%d)
CRITICAL_KEYWORDS=("CRITICAL" "FATAL" "segfault" "brute-force")
ALERT_LOG_FILE="/tmp/critical_alerts_$(date +%Y%m%d).txt"

# AWS Configuration (Ensure these are set via aws configure or env vars)
# AWS_REGION="us-east-1" 

Step 2: Implement the Archiving Logic

The first function locates files older than a specific threshold and uploads them to S3. We use find to locate files and aws s3 cp for transfer.

archive_old_logs() {
    echo "[$(date '+%Y-%m-%d %H:%M:%S')] Starting archiving process..."

    # Find files older than 7 days in the log directory
    find "$LOG_DIR" -name "*.log" -type f -mtime +7 | while read -r file; do
        echo "[$(date '+%Y-%m-%d %H:%M:%S')] Found old file: $file"

        # Construct S3 key path
        s3_key="syslogs/$(basename "$file").old.$DATE_SUFFIX"

        # Upload to S3
        if aws s3 cp "$file" "s3://$ARCHIVE_BUCKET/$s3_key" --region us-east-1; then
            echo "[$(date '+%Y-%m-%d %H:%M:%S')] Successfully archived: $file -> s3://$ARCHIVE_BUCKET/$s3_key"

            # Optional: Delete local file after successful upload to save space
            # rm "$file" 
        else
            echo "[$(date '+%Y-%m-%d %H:%M:%S')] Error uploading $file. Check AWS credentials." >&2
        fi
    done

    echo "[$(date '+%Y-%m-%d %H:%M:%S')] Archiving process complete."
}

Step 3: Implement Real-Time Alert Flagging

The second function scans the most recent logs for critical patterns. Since Bash regex can be limited, we will invoke Python inline for more robust pattern matching if needed, though standard Bash grep is often sufficient for simple keyword checks.

flag_critical_alerts() {
    echo "[$(date '+%Y-%m-%d %H:%M:%S')] Starting critical alert scan..."

    # Scan the most recent 3 log files (e.g., today and yesterday)
    find "$LOG_DIR" -name "*.log" -type f -mtime -1 | sort -r | head -n 3 | while read -r file; do
        echo "[$(date '+%Y-%m-%d %H:%M:%S')] Scanning: $file"

        # Use grep to find lines containing critical keywords
        # The -i flag makes it case-insensitive
        grep -i -E "${CRITICAL_KEYWORDS[*]}" "$file" > /dev/null 2>&1

        if [ $? -eq 0 ]; then
            # If matches found, print them and append to the alert log
            grep -i -E "${CRITICAL_KEYWORDS[*]}" "$file" | tee -a "$ALERT_LOG_FILE"
            echo "[$(date '+%Y-%m-%d %H:%M:%S')] [WARNING] Critical alerts detected in: $file" >> "$ALERT_LOG_FILE"
        fi
    done

    echo "[$(date '+%Y-%m-%d %H:%M:%S')] Alert scan complete. Check $ALERT_LOG_FILE for details."
}

Step 4: Main Execution Flow

Combine the functions and add error handling to ensure the script exits if a critical failure occurs.

main() {
    archive_old_logs
    flag_critical_alerts

    # Example of sending an email alert if the log file is not empty (using mail command)
    if [ -s "$ALERT_LOG_FILE" ]; then
        echo "Critical alerts found! Sending notification..."
        # mail -s "System Alert: Critical Logs Detected" admin@example.com < "$ALERT_LOG_FILE"
        echo "Notification sent to configured email address."
    fi
}

# Run the main function
main "$@"

Expected Results and Verification

When you execute this script, you should observe a structured output indicating progress.

Illustrative Output:

[2023-10-27 10:00:00] Starting archiving process...
[2023-10-27 10:00:01] Found old file: /var/log/syslog.20231020
[2023-10-27 10:00:05] Successfully archived: /var/log/syslog.20231020 -> s3://company-logs-archive/syslogs/syslog.20231020.old.2023-10-27
[2023-10-27 10:00:06] Archiving process complete.
[2023-10-27 10:00:07] Starting critical alert scan...
[2023-10-27 10:00:08] Scanning: /var/log/syslog
Oct 26 14:22:01 server kernel: [CRITICAL] Out of memory killer invoked.
[2023-10-27 10:00:09] [WARNING] Critical alerts detected in: /var/log/syslog
[2023-10-27 10:00:10] Alert scan complete.

To verify success, check the S3 bucket console to see the uploaded file and inspect /tmp/critical_alerts_*.txt to ensure alerts were captured. You can also run aws s3 ls s3://company-logs-archive/syslogs/ from the command line.

Common Errors and Troubleshooting

Several issues commonly arise when implementing this workflow:

  1. AWS Credentials Missing: The script will fail with an access denied error if ~/.aws/credentials is not configured or points to invalid keys.
    • Fix: Run aws configure and ensure the region matches your bucket location.
  2. Permission Denied: If the script runs as a non-root user but tries to read /var/log, it may fail depending on system security policies (e.g., AppArmor or SELinux).
    • Fix: Ensure the execution user has read permissions for the log directory (ls -ld /var/log).
  3. Regex Syntax Errors: In Bash, special characters in variables can break regex patterns if not escaped properly.
    • Fix: Use arrays for keywords and expand them carefully within double quotes, as shown in the flag_critical_alerts function.

Industry Application and Student Practice Task

Real-World Scenario

In a production environment, this script would typically be scheduled using cron. An industry practitioner might add a line to /etc/cron.daily/ to run the script every night at 2:00 AM. This ensures logs are archived before the disk fills up and that overnight security incidents are flagged immediately upon boot.

Student Practice Task

For students learning automation, try modifying the script to:
1. Compress the log files using gzip before uploading them to S3 to save storage costs. Update the archive_old_logs function to include gzip "$file" before the aws s3 cp command.
2. Add a Python snippet that uses the boto3 library to list objects in the S3 bucket and verify the upload programmatically, rather than relying solely on CLI exit codes.
3. Implement a “dry-run” mode using a flag (e.g., --test) that lists files to be archived without actually uploading them, useful for debugging before production deployment.

By mastering this Bash challenge, you gain practical experience in log management, cloud integration, and security monitoring—skills highly valued in both entry-level engineering roles and advanced DevOps positions.

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.