Linux & Shell Scripting
Master the operating system that powers 95% of cloud workloads. File systems, processes, systemd, bash scripting, hardening, and production-grade automation on WSL2.
Lesson objective
- What it teaches
- Architecture & How It Works · Core Components & Concepts · WSL Hands-On Lab · Real-World Project — Startup → Enterprise · Troubleshooting Guide · Predict the Result: Permissions, Signals and Links
- Why it matters
- A required lesson for DevOps Engineer, Cloud Engineer, SRE, DevSecOps Engineer, Container/Kubernetes Engineer, MLOps / LLMOps Engineer, Observability Engineer. See the role paths
- What you demonstrate
-
- Simulated lab: WSL Hands-On Lab: Run sudo apt update && sudo apt upgrade -y. Recorded as lab evidence.
- Predict 3 results this lesson prints. You mark each one yourself.
- Optional, real environment: 7 hands-on tasks on your own machine or an external lab site (checklist). Not tracked as evidence.
Architecture & How It Works 01.1
Linux is a monolithic kernel with modular drivers. User-space programs interact with the kernel exclusively through system calls. Understanding layers is critical for debugging containers, performance, and security.
nginx, node, bash] U2[Libraries
glibc, musl] U3[Shell & Tools] end subgraph "Kernel Space" K1[System Call Interface] K2[Process Scheduler
CFS] K3[Virtual File System
VFS] K4[Memory Manager
MMU + cgroups] K5[Network Stack
iptables/netfilter] end subgraph "Hardware" H1[CPU / Memory] H2[Storage
ext4 / xfs] H3[Network NICs] end U1 -->|syscalls| K1 U2 --> K1 K1 --> K2 & K3 & K4 & K5 K2 --> H1 K3 --> H2 K5 --> H3
Filesystem Hierarchy
/ is root. Key dirs: /etc (config), /var (logs/var data), /usr (binaries), /home, /proc (kernel state), /sys (devices).
Everything is a file. Devices appear under /dev. Mount points allow attaching filesystems.
Process Model
Every process has PID, PPID, UID/GID, file descriptors, and namespaces. systemd (PID 1) manages services via cgroups and units.
Signals, nice values, and OOM killer are essential for production stability.
Core Components & Concepts 01.2
| Domain | Tool / Command | Purpose | Key Example |
|---|---|---|---|
| File Permissions | chmod, chown, umask, getfacl | Control access. 755 vs 600 critical for keys. | chmod 600 ~/.ssh/id_rsa |
| Process Management | ps, top, htop, kill, pkill, nice, systemd | Identify leaks, restart services, control resources. | systemctl restart nginx |
| Networking | ss, ip, netstat, nmap, tcpdump, ufw | Inspect sockets, routes, firewall rules. | ss -tuln |
| Package Management | apt, yum/dnf, snap, dpkg, rpm | Install, upgrade, pin versions reproducibly. | apt update && apt install -y nginx |
| Storage & Disk | df, du, lsblk, fdisk, lsof, find | Diagnose full disks, find space hogs. | du -sh /* | sort -h |
| Scheduling | cron, at, systemd timers | Automate backups, cleanup, monitoring. | crontab -e |
apt-mark hold on critical packages in production.WSL Hands-On Lab 01.3
Complete WSL2 Production-Style Server Setup
Run these commands in Ubuntu-22.04 or 24.04 WSL2. All commands are copy-paste ready and tested.
Step 1 — Update system and install essentials
$ sudo apt update && sudo apt upgrade -y $ sudo apt install -y curl wget git vim htop tree ufw fail2ban $ sudo apt install -y build-essential python3-pip
Step 2 — Create a dedicated deploy user + SSH hardening
$ sudo adduser --disabled-password --gecos "" deploy $ sudo usermod -aG sudo deploy $ sudo mkdir -p /home/deploy/.ssh $ sudo chmod 700 /home/deploy/.ssh $ sudo touch /home/deploy/.ssh/authorized_keys $ sudo chmod 600 /home/deploy/.ssh/authorized_keys $ sudo chown -R deploy:deploy /home/deploy/.ssh
Step 3 — Create a production disk monitoring script
#!/bin/bash
# Production disk + memory monitor with alerts
THRESHOLD=80
LOG_FILE="/var/log/disk-alert.log"
HOSTNAME=$(hostname)
check_disk() {
USAGE=$(df / | awk 'NR==2 {print $5}' | tr -d '%')
if [ "$USAGE" -gt "$THRESHOLD" ]; then
MSG="[$HOSTNAME] CRITICAL: / is ${USAGE}% full at $(date)"
echo "$MSG" | tee -a "$LOG_FILE"
# Example: send to Slack or email in prod
# curl -X POST -H 'Content-type: application/json' \
# --data "{\"text\":\"$MSG\"}" "$SLACK_WEBHOOK"
fi
}
check_memory() {
MEM_USED=$(free | awk '/Mem:/ {printf "%.0f", $3/$2 * 100}')
if [ "$MEM_USED" -gt 85 ]; then
echo "[$HOSTNAME] WARNING: Memory at ${MEM_USED}%" | tee -a "$LOG_FILE"
fi
}
check_disk
check_memory
$ sudo cp disk-monitor.sh /usr/local/bin/ $ sudo chmod +x /usr/local/bin/disk-monitor.sh $ sudo /usr/local/bin/disk-monitor.sh
Step 4 — Schedule with systemd timer (preferred over cron)
$ sudo tee /etc/systemd/system/disk-monitor.service > /dev/null << 'EOF' [Unit] Description=Disk and Memory Monitor [Service] Type=oneshot ExecStart=/usr/local/bin/disk-monitor.sh User=root EOF $ sudo tee /etc/systemd/system/disk-monitor.timer > /dev/null << 'EOF' [Unit] Description=Run disk monitor every 5 minutes [Timer] OnBootSec=1min OnUnitActiveSec=5min Unit=disk-monitor.service [Install] WantedBy=timers.target EOF $ sudo systemctl daemon-reload $ sudo systemctl enable --now disk-monitor.timer $ sudo systemctl list-timers
Step 5 — Configure UFW firewall + fail2ban basics
$ sudo ufw default deny incoming $ sudo ufw default allow outgoing $ sudo ufw allow 22/tcp $ sudo ufw allow 80/tcp $ sudo ufw allow 443/tcp $ sudo ufw --force enable $ sudo ufw status verbose
Lab Checklist — Track Your Progress
- Update system and install base packages (curl, git, ufw, fail2ban, htop) Open Lab
- Create non-root deploy user with sudo and SSH key auth only
- Write and test disk-monitor.sh script (threshold 80%)
- Create and enable systemd timer for the monitor (every 5 min)
- Harden with UFW: allow 22/80/443, deny all else
- Complete SadServers "Santiago" scenario (Apache not serving) SadServers
- Complete Killercoda "Linux Basics" and "Taipei" (disk space) Killercoda
Real-World Project — Startup → Enterprise 01.4
Secure a fresh Ubuntu server for Node.js app
Goal: Make a single server production-ready for a Node API behind nginx.
$ sudo apt install -y nginx nodejs npm $ sudo ufw allow 'Nginx Full' $ sudo ufw allow OpenSSH $ sudo ufw enable $ sudo systemctl enable --now nginx # Deploy simple reverse proxy $ sudo tee /etc/nginx/sites-available/api << 'EOT' server { listen 80; server_name _; location / { proxy_pass http://localhost:3000; proxy_set_header Host $host; } } EOT $ sudo ln -s /etc/nginx/sites-available/api /etc/nginx/sites-enabled/ $ sudo nginx -t && sudo systemctl reload nginx
Ansible-compatible hardened baseline + monitoring script
Reusable script that can be executed by Ansible later. Includes unattended upgrades and auditd.
$ sudo apt install -y unattended-upgrades auditd $ sudo dpkg-reconfigure -plow unattended-upgrades $ echo "deploy ALL=(ALL) NOPASSWD: /usr/bin/systemctl" | sudo tee /etc/sudoers.d/deploy
Compliance scanning, automated patching, SELinux/AppArmor
apt-cacher-ng or satellite for patch management. Enable AppArmor profiles for nginx.$ sudo apt install -y lynis $ sudo lynis audit system --quick $ sudo apt install -y apparmor apparmor-profiles $ sudo aa-enforce /etc/apparmor.d/usr.sbin.nginx
Production security logging: auditd queries and redacted forwarding
Review exercise, not a host recording. Assumptions: Ubuntu 24.04 on WSL2 or a Linux VM, audit-userspace 3.1.2, a kernel built with CONFIG_AUDIT, systemd 255 and Vector 0.38.0. WSL kernels and unprivileged containers may lack audit support. Do not install services, add audit rules or ship logs for this exercise.
Reading /var/log/audit/audit.log needs filesystem permission, commonly root. Rule administration needs CAP_AUDIT_CONTROL; CAP_AUDIT_READ concerns multicast audit socket access, not all saved-file searches. Journal access also depends on group/ACL policy. Do not grant yourself capabilities or group membership to bypass a denial.
Rules to review with the host owner
The following are illustrative rule-file entries, not shell commands. The file watch records writes and attribute changes. The x86-64 exec rule is broad, can expose arguments and generate high volume; scope it to approved users and workload before use. It does not cover 32-bit compatibility syscalls. No rules are loaded here.
-w /etc/passwd -p wa -k identity_changes
-a always,exit -F arch=b64 -S execve -k command_executionSearch before interpreting
On an authorized audit host with readable logs, these read-only queries correlate keyed events, failed authentication and real UID 1000. Replace 1000 with the investigated UID; -ui filters real UID, not login UID. -i resolves numeric values using this machine's databases, which may differ from the original host. Keep raw evidence securely.
ausearch -k identity_changes -ts recent
aureport -au --failed -ts today
ausearch -k command_execution -ui 1000 -iSimulated audit fixture, not recorded output: numeric fields below illustrate a privileged file open attributed to login UID 1001. A real event may contain PATH, CWD and PROCTITLE records sharing the same serial; inspect them together before concluding what changed.
type=SYSCALL msg=audit(1710000000.000:42): arch=c000003e syscall=257 success=yes exit=3 a0=ffffff9c a1=0 a2=241 a3=1b6 items=0 ppid=1234 pid=5678 auid=1001 uid=0 gid=0 euid=0 key="identity_changes"auid is the login identity (normally retained through sudo); uid/euid are real/effective identities. Interpret syscall 257 only with its x86-64 arch: openat. Here exit=3 is a returned file descriptor, not a process exit status. success=yes alone does not establish an unauthorized change. The key comes from a matching rule.
Expected checks and recovery: no matches can mean wrong time zone/window, rotated logs, missing rules, lost events or simply no activity. Inspect collection health with the authorized operator; do not infer “no incident.” A permission error is an access boundary. Search the synthetic fixture locally with ausearch -if audit-fixture.log -k identity_changes --raw only after saving it in your scratch directory; expect the serial 42 record, then delete that scratch file. This parser check has not been run here.
Forward a minimal event, discard raw text
This configuration sketch reads journald and emits only an allowlisted constant message. This deliberately removes the entire original message, Authorization/Bearer values, passwords, arguments and other arbitrary fields, including unknown secret formats. It sacrifices detail for a safe teaching boundary. Production redaction needs an approved schema and synthetic tests for every retained field; regex replacement alone is insufficient.
sources:
journal:
type: journald
transforms:
redact:
type: remap
inputs: [journal]
drop_on_error: true
drop_on_abort: true
reroute_dropped: false
source: |
. = {"message": "[REDACTED]", "source": "linux-journal"}
sinks:
collector:
type: http
inputs: [redact]
uri: https://collector.example.invalid/ingest
encoding:
codec: json
tls:
verify_certificate: true
verify_hostname: trueOffline verification: with Vector 0.38.0 already available, save this as vector.yaml and run vector validate --no-environment vector.yaml to check topology without collector health checks. Do not start the configuration. The reserved .invalid endpoint is intentional; no collector or credentials are provided. Validation and VRL execution remain unrun here.
For an offline redaction test, feed synthetic messages such as Authorization: Bearer TEST_ONLY password=TEST_ONLY, nested secret fields and multiline text into the remap transform using Vector's unit-test facility. Expected event: exactly the two constant fields shown above, with no TEST_ONLY and no original fields. Include an error/abort case if the transform is extended; dropped events must never reach a raw fallback sink.
Deployment prerequisites and recovery: an operator must approve journal access, journalctl availability, collector payload/framing contract, trusted CA, DNS and egress. Journald does not automatically collect raw audit.log; audit collection needs its own approved pipeline. Inspect local Vector errors and collector acknowledgements before claiming delivery. Certificate or hostname failures require fixing trust/name configuration, never disabling TLS checks. If delivery backs up, pause forwarding and inspect buffer/drop policy and disk space; preserve restricted local evidence. No service is started here, so cleanup is limited to deleting your scratch configuration and fixture.
Official references: audit-userspace 3.1.2 ausearch, aureport, auditctl rules, Vector 0.38.0 component specifications and Vector unit-test reference (current; check against 0.38.0).
Troubleshooting Guide 01.5
Unprivileged diagnostics: permissions, process state and loopback
Runnable exercises, not recorded results. Use an ordinary user on WSL2 Ubuntu 24.04 or a disposable Linux VM, Bash 5.2, GNU Coreutils 9.4 and Python 3.12 (examples use APIs documented in Python 3.10+). No sudo, packages, firewall changes or external connections are needed. Stop if a prerequisite is missing; these commands have not been run on a Linux host in this session. Local alternative practice: SadServers.
Permission failure with a bounded scratch file
Paste the entire subshell in Bash. It refuses UID 0 because root can bypass ordinary permission checks. Work only on a fresh mktemp directory; never substitute a production path.
(
set -eu
[ "$(id -u)" -ne 0 ] || { echo 'Use an ordinary user'; exit 1; }
scratch=$(mktemp -d)
trap 'chmod 600 "$scratch/probe" 2>/dev/null || :; rm -f -- "$scratch/probe"; rmdir -- "$scratch"' EXIT
umask 077
printf 'local-only\n' > "$scratch/probe"
stat -c '%a %U %n' "$scratch/probe"
chmod 000 "$scratch/probe"
if cat "$scratch/probe"; then
echo 'Unexpected read: investigate ACLs/capabilities/filesystem'; exit 1
fi
chmod 600 "$scratch/probe"
test "$(cat "$scratch/probe")" = local-only
stat -c '%a %U %n' "$scratch/probe"
)Expected checks: initial/final mode 600, owner is your user; the middle read fails with Permission denied. Success at mode 000 means the test is invalid under your filesystem or capabilities. Restore mode 600 before investigating; avoid Windows-mounted paths with different permission semantics. EXIT removes only the known scratch file and its empty directory. Verify that printed scratch path no longer exists. No recursive delete is used.
A tiny TCP listener, then a deliberate refusal
Run python3 loopback.py after saving this block. Port 0 asks the kernel for a free port. Both sockets bind explicitly to 127.0.0.1; nothing listens on a public interface. The second bound socket never calls listen, so the connect is expected to be refused. Numeric addresses exclude DNS from this test.
import errno
import socket
with socket.socket() as listener:
listener.bind(("127.0.0.1", 0))
listener.listen(1)
listener.settimeout(2)
address = listener.getsockname()
print("Listening only on", address)
with socket.create_connection(address, timeout=2) as client:
with listener.accept()[0] as peer:
peer.settimeout(2)
client.sendall(b"probe")
assert peer.recv(5) == b"probe"
peer.sendall(b"OK")
assert client.recv(2) == b"OK"
print("Local connect and response checked")
with socket.socket() as stopped:
stopped.bind(("127.0.0.1", 0))
with socket.socket() as client:
client.settimeout(2)
result = client.connect_ex(stopped.getsockname())
assert result == errno.ECONNREFUSED, result
print("Non-listening socket correctly refused")
# Context managers close every socket, including on assertion failure.Expected checks and recovery: the three messages appear with a variable ephemeral port, and assertions pass. A timeout indicates local filtering or a stalled runtime; it is different from an immediate refusal. A policy denial is not permission to disable a firewall. A successful TCP check proves only local reachability and this two-byte reply, not DNS, routing, TLS or remote service health. Inspect traceback and the binding address before retrying. Exiting closes sockets; delete only your saved loopback.py when finished.
Official references: GNU Coreutils permission commands (current manual; Ubuntu 24.04 assumption: 9.4), Bash trap and shell builtins (5.2-compatible subset), Python 3.10 socket API. Check installed versions with bash --version, stat --version and python3 --version before adapting the exercises.
OOM evidence and TERM before KILL
Read-only diagnosis and simulated evidence. Assumptions: Linux 6.8 cgroup v2 unified mount at /sys/fs/cgroup, systemd 255 with a readable journal and an existing operator-approved service named app.service. This name is illustrative: inspect the actual unit you own. WSL2 may not run systemd, expose memory controllers or retain kernel logs. Missing files and denied access mean unavailable evidence, not zero pressure. Never allocate memory to induce host OOM.
journalctl -k -b --since '-1 hour' --no-pager --case-sensitive=no --grep='out of memory|oom-killer|killed process'
systemctl show app.service -p ControlGroup -p Result -p ExecMainCode -p ExecMainStatus
# Use the returned ControlGroup, never guess a service's cgroup path.
cg=$(systemctl show app.service -p ControlGroup --value)
if [ -n "$cg" ] && [ "$cg" != / ]; then
for metric in memory.current memory.high memory.max memory.events memory.events.local; do
printf '%s\n' "$metric"
cat "/sys/fs/cgroup$cg/$metric"
done
fiSimulated incident worksheet, not a kernel recording: suppose a journal entry reports “Memory cgroup out of memory: Killed process 4242 (app), total-vm:2097152kB, anon-rss:524288kB, file-rss:4096kB”, and successive memory.events snapshots show oom 2→3 and oom_kill 0→1. Correlate time, PID, unit and cgroup before attributing a failure. A status of 137 alone is not proof of OOM; it can also follow an explicit KILL.
For Linux 6.8: memory.current is current charged usage; memory.high applies reclaim pressure/throttling, while memory.max is a hard limit. memory.events includes descendants; memory.events.local isolates this cgroup. An oom increase records an OOM condition, not necessarily a kill; oom_kill counts kills by any OOM killer. Compare counter deltas over the incident window. A later low current value does not exclude a prior OOM.
total-vm is virtual address space, not resident RAM. anon-rss and file-rss describe resident anonymous and file-backed pages. Victim selection also depends on eligibility, workload footprint and oom_score_adj; the largest virtual size alone does not establish the cause. Read the full kernel report for global versus memory-cgroup scope. Capture restricted evidence before restart, check workload demand/leaks and budget, and obtain capacity approval before changing limits.
A service policy to review, not apply
These systemd 255 unit fragments belong in an existing service's [Service] section. MemoryHigh is the first pressure boundary; MemoryMax is the last boundary. OOMScoreAdjust changes selection preference, not immunity. TimeoutStopSec bounds the stop phase; service-specific shutdown and KillMode still matter. No daemon-reload or restart is part of this exercise.
[Service]
MemoryHigh=800M
MemoryMax=1G
OOMScoreAdjust=-200
TimeoutStopSec=30sObserve one owned child, then stop it gracefully
Run python3 graceful-stop.py on unprivileged Linux with Python 3.10+. This starts only its own sleeping child, inspects its /proc state, sends TERM and waits ten seconds before considering KILL. Popen retains child ownership; this is not a script for arbitrary copied PIDs. Managed services should use their operator-approved stop procedure instead.
import os
from pathlib import Path
import signal
import subprocess
import sys
assert sys.platform.startswith("linux") and os.geteuid() != 0
child = subprocess.Popen([sys.executable, "-c", "import time; time.sleep(60)"])
try:
status = Path(f"/proc/{child.pid}/status").read_text()
print(next(line for line in status.splitlines() if line.startswith("State:")))
child.terminate() # SIGTERM on POSIX
try:
result = child.wait(timeout=10)
assert result == -signal.SIGTERM, result
print("TERM completed; KILL not needed")
except subprocess.TimeoutExpired:
child.kill() # SIGKILL only after grace period
result = child.wait(timeout=2)
assert result == -signal.SIGKILL, result
print("Grace expired; child killed and reaped")
finally:
if child.poll() is None:
child.terminate()
try:
child.wait(timeout=10)
except subprocess.TimeoutExpired:
child.kill()
child.wait(timeout=2)Expected checks: state may be R (running) or S (sleeping); normally TERM completes and KILL is unused. Python return codes -15/-9 represent signal termination; Bash conventionally reports 143/137. TERM allows handlers to flush and exit; KILL cannot be caught. This demonstration does not exercise the KILL branch unless the grace period expires. No process is left deliberately; wait reaps the child, and finally repeats bounded cleanup after an assertion failure. Delete only the saved script afterward.
Recovery limits: a Z state is an exited zombie awaiting its parent's wait, so another KILL does not reap it. A D state can mean uninterruptible I/O sleep; even KILL may wait on kernel I/O completion. If the final wait times out, inspect the owned PID's /proc state and underlying storage with the host operator; do not repeatedly signal unrelated PIDs or restart the host. A reused PID makes ad hoc kill -0 polling unsafe. No kernel OOM or stuck-I/O experiment is performed here.
Official references: Linux 6.8 cgroup v2 memory interface, Linux 6.8 /proc state and OOM scoring, systemd 255 journalctl, resource-control, service stop semantics, Python 3.10 Popen signal and wait APIs and Bash exit status.
Disk full (df/du/find)
$ df -h $ sudo du -ah / | sort -rh | head -20 $ sudo find /var/log -type f -name "*.log" -mtime +7 -delete
Process eating CPU (top/htop/kill)
Use htop (install if missing). Identify PID, renice or kill.
$ htop $ sudo kill -9 <PID> $ systemctl status <service>
Service not starting (systemctl / journalctl)
$ sudo systemctl status nginx $ sudo journalctl -u nginx -xe --no-pager | tail -50 $ sudo nginx -t
SSH connection refused / Permission denied
- Check:
sudo systemctl status ssh - Check:
sudo ufw status— port 22 open? - Check:
tail -f /var/log/auth.logfor PAM or key errors - Fix:
sudo chmod 600 ~/.ssh/authorized_keys
30-Day Learning Roadmap 01.6
- Navigate and explain /proc /sys /etc
- Master chmod, chown, umask, ACLs
- Practice find + xargs + rsync
- Complete SadServers Santiago
- ps, top, lsof, ss deep dive
- systemd units, timers, sockets
- ufw + nftables basics
- Write first monitoring script
- Bash: arrays, functions, traps
- Write idempotent scripts
- Systemd timers vs cron
- Log rotation + alerting
- SSH key-only + fail2ban
- Lynis + CIS benchmarks
- AppArmor / SELinux profiles
- Enterprise patch automation
Predict the Result: Permissions, Signals and Links 01.7
Recorded from a real run of scripts/recordings/linux.sh; every output below is pasted from scripts/recordings/linux.out. Cover the output, predict it, then compare.
Environment: Ubuntu 24.04 container, running as root in /tmp.
# Mode string and octal for a file set to 640 $ touch report.txt && chmod 640 report.txt && stat -c '%A %a' report.txt -rw-r----- 640 # A new file under umask 077 $ umask 077 && touch app.log && stat -c '%A %a' app.log -rw------- 600 # Exit status of a process killed by SIGTERM $ sleep 300 & kill -TERM $!; wait $!; echo $? 143 # Reading through a symlink whose target was deleted $ echo v1 > release.txt && ln -s release.txt current && rm release.txt && cat current; echo $? cat: current: No such file or directory 1
SIGTERM is signal 15, and a shell reports death by signal N as 128 + N, so 143. A symlink stores a path, not the file: delete the target and every reader of the link gets No such file or directory, a common cause of broken "current release" links after cleanup jobs.