Skip to main content

Lesson 8 of 10

Bash Scripting for Security Automation

Bash scripting enables security professionals to automate repetitive tasks - from scheduled vulnerability checks to incident response procedures. A good security script can save hours of manual work and ensure consistent, repeatable processes.

60 minBy Priygop Editorial TeamUpdated 2026Peer Reviewed & Verified

Bash Scripting Security Fundamentals

Bash Scripting Security Fundamentals
#!/bin/bash
# Best practices for security scripts

set -euo pipefail
# -e: Exit immediately if a command fails
# -u: Treat unset variables as errors (prevents logic bugs)
# -o pipefail: Pipe failure propagates (grep | awk failures are caught)

# Use full paths to prevent PATH-hijacking attacks
NMAP="/usr/bin/nmap"
AWK="/usr/bin/awk"
GREP="/bin/grep"

# Validate inputs before using them
TARGET="${1:-}"
if [[ -z "$TARGET" ]]; then
    echo "Usage: $0 <target-ip>" >&2
    exit 1
fi

# Validate IP address format
if ! [[ "$TARGET" =~ ^[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}$ ]]; then
    echo "Error: Invalid IP address format" >&2
    exit 1
fi

# Log all actions (for audit trail)
LOGFILE="/var/log/security_scan_$(date +%Y%m%d_%H%M%S).log"
exec > >(tee -a "$LOGFILE") 2>&1
echo "Scan started at $(date) by $(whoami)"

Security Monitoring Script

Security Monitoring Script
#!/bin/bash
# security_monitor.sh - Detect suspicious activity on a Linux server
# Run via cron: */15 * * * * /usr/local/bin/security_monitor.sh

set -euo pipefail
ALERT_EMAIL="security@company.com"
REPORT="/tmp/security_report_$(date +%Y%m%d_%H%M%S).txt"

echo "=== Security Monitor Report ===" > "$REPORT"
echo "Generated: $(date)" >> "$REPORT"
echo "Host: $(hostname)" >> "$REPORT"
echo "" >> "$REPORT"

# 1. Check for failed SSH logins (brute force detection)
echo "=== Failed SSH Attempts (last 15 min) ===" >> "$REPORT"
journalctl -u ssh --since "15 minutes ago" | grep "Failed password"     | awk '{print $(NF-3)}' | sort | uniq -c | sort -rn >> "$REPORT"

# 2. Check for new listening ports
echo "" >> "$REPORT"
echo "=== Listening Ports ===" >> "$REPORT"
ss -tlnp | grep LISTEN >> "$REPORT"

# 3. Check for active outbound connections to suspicious ports
echo "" >> "$REPORT"
echo "=== Established Connections ===" >> "$REPORT"
ss -tnp | grep ESTABLISHED | grep -v "127.0.0.1" >> "$REPORT"

# 4. Check for recently modified files in sensitive directories
echo "" >> "$REPORT"
echo "=== Recently Modified System Files ===" >> "$REPORT"
find /etc /bin /usr/bin /sbin /usr/sbin -mmin -60 -type f 2>/dev/null >> "$REPORT"

# 5. Check for SUID files (potential privilege escalation)
echo "" >> "$REPORT"
echo "=== SUID Binaries ===" >> "$REPORT"
find / -perm -4000 -type f 2>/dev/null | grep -v proc >> "$REPORT"

# Send alert if suspicious activity found
if grep -q "Failed password" "$REPORT"; then
    mail -s "SECURITY ALERT: Failed SSH attempts on $(hostname)"         "$ALERT_EMAIL" < "$REPORT"
fi

echo "Report: $REPORT"

Common Mistakes

  • Not using 'set -euo pipefail' - without these flags, scripts continue running after errors, potentially causing security issues from partial execution
  • Using relative paths in security scripts - an attacker can manipulate PATH to make your script call malicious binaries; always use absolute paths
  • Hard-coding credentials in scripts - even in 'private' scripts, credentials should come from environment variables or a secrets manager
  • Running security scripts as root unnecessarily - use the minimum privilege level required; scripts that only need to read logs should not run as root

Tip

Tip

Practice Bash Scripting for Security Automation in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.

Diagram
Loading diagram…

The foundational security model: Confidentiality (privacy), Integrity (trust), and Availability (uptime).

Practice Task

Note

Practice Task - (1) Write a working example of Bash Scripting for Security Automation from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.

Quick Quiz

Common Mistake

Warning

A common mistake with Bash Scripting for Security Automation is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready cybersecurity code.

Key Takeaways

  • Bash scripting enables security professionals to automate repetitive tasks - from scheduled vulnerability checks to incident response procedures.
  • Not using 'set -euo pipefail' - without these flags, scripts continue running after errors, potentially causing security issues from partial execution
  • Using relative paths in security scripts - an attacker can manipulate PATH to make your script call malicious binaries; always use absolute paths
  • Hard-coding credentials in scripts - even in 'private' scripts, credentials should come from environment variables or a secrets manager

Hands-on Practice Tools for this Course

Test what you learn using these free in-browser developer utilities (no signup required).

All 40+ Tools

Topics in This Module

0/10 done