Objective. Students write Bash scripts that parse system and auth logs to extract security-relevant events and generate a plain-text audit report.
This lesson, its worked examples and its practice questions has not yet been verified by an industry-certified professional or by a certification or approval body. It is a study draft and may contain errors. Do not use it as instructions for work on a job site or on live equipment. Always follow your instructor, your supervising professional, and current official references and regulations.
VoTechWorks program approval and accreditation are still in progress. Credentials are issued only by the certifying bodies named in each program, after their own exams.
System logs are among the most valuable sources of evidence available to a security analyst. Every failed login, every privilege escalation, and every unexpected service restart leaves a trace in a log file. The ability to extract that evidence quickly — using lightweight command-line tools rather than expensive platforms — is a core skill tested by CompTIA CySA+ and expected in entry-level analyst roles.
On Ubuntu and most Debian-based Linux systems, the file `/var/log/auth.log` records authentication events: successful and failed SSH logins, sudo usage, and PAM (Pluggable Authentication Module) activity. A single busy server can generate thousands of lines per day. Manual reading is impractical; Bash scripting automates the extraction of exactly what you need.
grep searches text for lines matching a pattern. The `-E` flag enables extended regular expressions. For example:
```bash
grep "Failed password" /var/log/auth.log
```
This returns every line recording a failed SSH password attempt.
awk processes text field by field. Fields are separated by whitespace by default. In a typical `auth.log` failed-login line, the source IP address appears after the word `from`. The command `awk '{print $NF}'` prints the last field on each line, while `awk '/from/{print $(NF-3)}'` can target the IP more precisely depending on log format. Always inspect a sample of actual lines first to confirm field positions.
cut slices fields from structured text using a delimiter you specify with `-d`, selecting the field with `-f`. It is useful when log lines have a consistent delimiter such as a colon or comma.
sort arranges lines alphabetically or numerically. The `-n` flag sorts numerically and `-r` reverses the order so the highest count appears first. Combining `sort -rn` with `uniq -c` (which prepends a count of repeated lines) is the classic recipe for frequency analysis.
A well-structured Bash script follows a clear pattern: shebang line, variable declarations, functions, and a main execution block.
```bash
#!/usr/bin/env bash
LOGFILE="${1:-auth.log}" # Accept log path as argument; default to auth.log
THRESHOLD=10
REPORT="audit_$(date +%Y%m%d_%H%M%S).txt"
BLOCKLIST="blocklist.txt"
grep "Failed password" "$LOGFILE" \
| grep -oE '([0-9]{1,3}\.){3}[0-9]{1,3}' \
| sort \
| uniq -c \
| sort -rn > /tmp/ip_counts.txt
{
echo "Login Audit Report — $(date)"
echo "Log file: $LOGFILE"
echo "Threshold: $THRESHOLD failed attempts"
echo "-----------------------------------"
while read -r count ip; do
if [ "$count" -gt "$THRESHOLD" ]; then
echo "FLAGGED $ip ($count attempts)"
fi
done < /tmp/ip_counts.txt
} > "$REPORT"
echo "Report saved to $REPORT"
```
The regex `([0-9]{1,3}\.){3}[0-9]{1,3}` matches IPv4 addresses. Using `grep -oE` prints only the matching portion of each line, not the whole line.
Once you have flagged IPs, the next analyst task is to check whether they are already known threats. A local block-list is a plain-text file with one IP per line. A Bash function can automate this check:
```bash
check_blocklist() {
local ip="$1"
if grep -qF "$ip" "$BLOCKLIST" 2>/dev/null; then
echo "BLOCKED $ip"
else
echo "ALERT $ip (not in block-list — investigate)"
fi
}
```
Call this function inside the flagging loop to append status to each flagged IP in the report. The `-q` flag makes grep silent (no output, just an exit code); `-F` treats the search string as a fixed string, not a regex, which is safer for IP addresses.
Always quote variables (`"$VARIABLE"`) to prevent word-splitting errors when paths contain spaces. Redirect stderr to avoid leaking error messages into report files unintentionally — or capture it deliberately with `2>&1` if you want to log errors. Never run audit scripts with root privileges unless the log file requires it; read-only access to log files is sufficient and reduces risk. Validate that input files exist before processing them:
```bash
[ -f "$LOGFILE" ] || { echo "Error: log file not found"; exit 1; }
```
In a lab environment, work only on provided sample files, not live production logs, unless explicitly authorized. Unauthorized access to logs on systems you do not own or administer may violate federal law under the Computer Fraud and Abuse Act and equivalent state statutes.
CompTIA CySA+ emphasizes log analysis as a foundational threat-detection skill. Analysts are expected to identify indicators of attack from log data, correlate events across sources, and document findings. The script you build in this lab directly practices those competencies: extraction, aggregation, threshold-based flagging, and cross-referencing against known threat data.
Answer each question, then check it. Nothing is recorded; this is your own practice.
A free tech program — complimentary, as our commitment to get America working. Help us build VoTechWorks. Tell us what works, what doesn’t, and what you want to learn.