Linux Lesson 1: Core Fundamentals
This is the first course in the DevOps learning path: Linux → Bash → Git → Docker → Kubernetes → Terraform → Ansible → GitHub → GitLab → Azure DevOps → Jenkins → Azure Landing Zone → AKS → Helm → GitOps and Argo CD → Prometheus & Grafana. No prior course is required; basic familiarity with files and directories is enough. Later courses build on the shell, permissions, process management, and package skills covered here. Next, continue with Learn Bash in 8 Hours.
- Explain the boundary between the kernel and user space, including system calls, processes, and file descriptors. Identify the Linux families, package formats, and support lifecycles used by Ubuntu, Rocky Linux, AlmaLinux, Azure Linux, and Amazon Linux 2023.
- Trace a command end to end: shell parsing and expansion → executable lookup through
PATH→ process creation withfork/execve→ system calls → permission checks → exit status andwait. The first core animation walks through this sequence. - Use Bash quoting, expansion, redirection, pipelines, history, and completion. Use the Filesystem Hierarchy Standard (FHS) to find where configuration, logs, programs, and data belong.
- Read and set permissions, ownership,
umask, ACLs, and special bits (SUID, SGID, and sticky). Apply Linux's access-check order to determine whether a user can reach or modify a file. - Manage users, groups and sudo:
/etc/passwd,/etc/shadow,/etc/group,/etc/sudoers.d/, understand Ubuntu 26.04 default sudo-rs and traditional sudo difference. - Observe and control process:
ps,top,/proc, signals, job control (&,jobs,fg,bg,nohup). - Use apt (deb822
.sourcesformat) and dnf to install, query, fix, and roll back software packages, and understand warehouse signatures andSigned-By. - Analyze the logs with the grep / sed / awk / sort / uniq / cut / xargs combination pipeline; do a final system readiness review and manually run myapp (port 5000) as system user
myappin/opt/myapp- Lesson 2 will turn this intomyapp.service.
1-hour time allocation table
| # | Time | Module | Core content | Animation/Interaction | Experiment (~/linuxlab) |
|---|---|---|---|---|---|
| 0 | Before class | Environment preparation | Multipass creation linuxlab (Ubuntu 26.04 LTS), administrator labadmin, working directory, optional rhellab | Environment self-check list | can log in as labadmin and sudo |
| 1 | 00–06 | Linux Architecture | Kernel/user space/system call/release family and support cycle | Core Animation 1: The whole process of executing a command | uname, /etc/os-release, strace See system calls |
| 2 | 06–13 | Shell and FHS | Bash parsing with 7 types of expansion, quotes, redirects, pipes, PATH, FHS directory responsibilities | Shell expansion step-by-step demonstration | Build ~/linuxlab directory tree, practice redirection |
| 3 | 13–21 | Permissions and ACL | rwx, ownership, umask, ACL and mask, SUID/SGID/sticky, capabilities | Core Animation 2: Permission determination + chmod / umask calculator | Shared directory /srv/share and ACL |
| 4 | 21–28 | Users, groups and sudo | passwd / shadow / group, system user, sudoers.d, sudo-rs | sudo authorization process | Create user alice / bob, group devs, restricted sudo rules |
| 5 | 28–35 | Processes and signals | Process tree, status, /proc, signals, job control, nohup | Process state machine + signaling | Foreground and background switching, SIGTERM vs SIGKILL |
| 6 | 35–42 | Software package management | apt and deb822 sources, signatures, dpkg; dnf and .repo; version fixation and rollback | apt install full process | Installing redis-server, python3-venv, query and fixation |
| 7 | 42–50 | Text processing | grep regular, sed replacement and in-place editing, awk fields and aggregation, sort / uniq / xargs | Pipeline step-by-step simulator | Analysis of access logs: Top IP, 5xx, P95 |
| 8 | 50–60 | Readiness review and troubleshooting | 12 system readiness review; the order of locating common errors | Readiness scorecard + interactive troubleshooting tree | Deliberately create 4 faults and fix them |
| — | After class | Cheat Sheet · Comprehensive Experiment | Manually deploy and accept the myapp user in /opt/myapp | Final Test (12 Question) | myapp returns /healthz |
Knowledge Coverage Matrix
| Target skills | M1 | M2 | M3 | M4 | M5 | M6 | M7 | M8 | Key commands | Experimental |
|---|---|---|---|---|---|---|---|---|---|---|
| Explaining kernel/user space/system calls | ✓ | ✓ | ✓ | · | ✓ | · | · | ✓ | uname -r, strace | M1 |
| Identifying release and support period | ✓ | · | · | · | · | ✓ | · | ✓ | /etc/os-release, pro status | M1, M8 |
| Bash expansion, quotes, redirection, pipes | ✓ | ✓ | · | · | ✓ | · | ✓ | ✓ | set -x, type, 2>&1 | M2, M7 |
| FHS Locating files | · | ✓ | ✓ | ✓ | · | ✓ | · | ✓ | ls /etc /var/log, dpkg -L | M2, comprehensive experiment |
| Permissions, umask, ACL, special bits | ✓ | · | ✓ | ✓ | · | · | · | ✓ | chmod, setfacl, namei -l | M3, comprehensive experiment |
| User, group, sudo | · | · | ✓ | ✓ | · | · | · | ✓ | useradd, visudo, sudo -l | M4, comprehensive experiment |
| Process, signal, job control | ✓ | ✓ | · | · | ✓ | · | · | ✓ | ps, kill, jobs | M5, comprehensive experiment |
| apt / dnf and warehouse | ✓ | · | · | · | · | ✓ | · | ✓ | apt, dpkg, dnf | M6, comprehensive experiment |
| Text processing and log analysis | · | ✓ | · | · | · | · | ✓ | ✓ | grep, sed, awk | M7 |
| System readiness review and troubleshooting | · | · | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | df -h, ss -ltnp, journalctl | M8 troubleshooting tree |
What is excluded from this lesson (and where to learn it)
| Topic | Why not in this lesson | Where to learn |
|---|---|---|
| systemd unit, journald, LVM, mount, network, SSH Reinforcement, cron / timer | Belongs to system management, you need to master the basics of this course first | Lesson 2: System management and production readiness |
| Cloud Linux: cloud-init, managed disks, Entra ID login, Azure Monitor Agent | Azure subscription required | Lesson 3 (Azure) |
| EC2, Amazon Linux 2023, IMDSv2, SSM, CloudWatch Agent | AWS account required | Lesson 4 (AWS) |
Bash script engineering (set -euo pipefail, trap, ShellCheck), Packer | Belongs to automation | Lesson 5 |
| SELinux / AppArmor, firewall, PAM, auditd, namespaces and cgroups | Security and kernel mechanisms | Lesson 6 Lesson; from the container perspective, see Docker Lesson |
| Performance analysis, strace / perf / eBPF in-depth, startup failure | In-depth troubleshooting | No. 7 class; for indicator monitoring, see Prometheus & Grafana class |
| Batch configuration of multiple hosts | Belongs to configuration management | Ansible course |
How to use this courseware
Principle · Diagram · Animation · Command · Experiment · Production case · Troubleshooting · Quizzes · Voice · Video. It is recommended to read "Principle" and "Animation" first, and then do "Experiments" on
linuxlab . The "Execute a Command" animation in Module 1 and the "Permission Determination" animation in Module 3 are the two main threads of the entire course, and each subsequent module will return to them. Test score ≥ 70% or click "Mark this module completed" will be counted as progress and saved in the local storage of this browser (it will be cleared after refreshing when the browser prohibits local storage).
The "Voice" tab uses the browser's built-in Web Speech API (en-US) to read the explanation script, and English terms are pronounced in en-US; the explanation script can still be read when there is no Chinese voice package, or it can be handed over to the TTS tool to generate audio.
apt-key Removed),Bash 5.3, Python 3.14. 26.04 defaults sudo-rs as sudo, rust-coreutils(uutils)provides most of the core tools (cp, mv, rm, df, true Still from GNU). If you are using 24.04 LTS (kernel 6.8, systemd 255, APT 2.7, Python 3.12, GNU coreutils, traditional sudo), the commands in this lesson are also applicable, and the differences will be marked with "24.04:". The RHEL system is compared to Rocky Linux / AlmaLinux 10.x (RHEL 10.3 was released on 2026-11-11; the latest official version of Rocky at the time of verification is 10.2), and the package manager is dnf 4.20 (dnf5 is currently used in Fedora). Upstream kernel: stable 7.3.x, longterm 6.18/6.12/6.6/6.1/5.15/5.10. Module 0 · Environment Preparation (completed before class)
linuxlab (Ubuntu Server 26.04 LTS), administrator user labadmin, working directory ~/linuxlab. Lessons 1–4 are all conducted on this machine (or its “twin” in the cloud)- A Windows 10/11, macOS or Linux computer with available memory ≥ 8 GB (4 GB for virtual machine), available disk ≥ 25 GB, CPU supports and hardware virtualization (VT-x / AMD-V in BIOS/UEFI) is enabled.
- Can install software as an administrator. No cloud account required (only required for Lessons 3 and 4).
- This course is the first course in the route and has no prerequisite courses; Lesson 2 will directly reuse the
linuxlab,labadmin,~/linuxlaband/opt/myappof this course.
Unified agreement for the whole course (consistent for lessons 1–4)
| Project | Agreed value | Explanation |
|---|---|---|
| Experimental machine | Hostname linuxlab, Ubuntu Server 26.04 LTS (24.04 also available) | 2 vCPU / 4 GB RAM / 20 GB disk |
| Admin | labadmin (in the sudo group) | Use it for daily operations, do not log in directly with root |
| Working directory | ~/linuxlab (i.e. /home/labadmin/linuxlab) | Script, sample log, myapp source code |
| Example application | myapp (Flask + gunicorn + Redis), port 5000, /healthz | System user myapp, installation directory /opt/myapp, virtual environment /opt/myapp/venv, configure /etc/myapp/myapp.env |
| RHEL system control (optional) | Host name rhellab, Rocky Linux or AlmaLinux 10.x | Only used for comparison dnf / firewalld / SELinux |
| Lesson 2 | The same linuxlab | turn myapp into myapp.service; LVM Experiment with a loop device (loop) to simulate an additional disk |
| Lesson 3 / 4 | Azure: rg-linux-lab / canadacentral / vm-linux-lab; AWS: ca-central-1 / Name=linux-lab / Amazon Linux 2023 | Use cloud-init / user data to reproduce the local myapp deployment |
Method A (recommended): Multipass
Multipass is Canonical's lightweight virtual machine manager (latest version 1.17.1 at time of verification), which uses Hyper-V or VirtualBox on Windows, the Apple virtualization framework on macOS, and QEMU/KVM on Linux. After installing from canonical.com/multipass/install:
data-l="bash"
class="out" data-l="Expected output (example)"
launch's -c/--cpus (default 1), -m/--memory (default 1G, minimum 512M), -d/--disk (default 5G, minimum 1G) are all from the official CLI reference; the image parameter can be a codename, alias or version number. Multipass will set the instance name to the hostname, so the hostname is linuxlab. If you can only use 24.04, replace 26.04 with 24.04.
Create administrator labadmin
The default user for Multipass is ubuntu. We create labadmin as agreed in the whole course and use it in the future:
data-l="bash"
class="out" data-l="Expected output (example)"
data-l="bash"
< redirection is not available in Windows PowerShell. You can change it to: Get-Content $HOME\.ssh\linuxlab.pub | multipass exec linuxlab -- sudo -u labadmin bash -c '...', IP directly from multipass info linuxlab Copy.
Method B: Hyper-V / VirtualBox / VMware + Official ISO
- Download Ubuntu Server 26.04 LTS from ubuntu.com/download/server ISO, create a new virtual machine: 2 vCPU, 4 GB memory, 20 GB disk (for Hyper-V, select Generation 2 virtual machine and set the secure boot template to "Microsoft UEFI Certificate Authority").
- In the installation wizard: fill in
linuxlabfor the server name,labadminfor the user name (the first user created by the installer is automatically in thesudogroup), and check Install OpenSSH server. - Just use NAT/default switch for the network; when you need to SSH from the host, use bridge or port forwarding (VirtualBox: NAT port forwarding 2222 → 22).
Method C: WSL2 (available, but with restrictions)
- Use
wsl --list --onlineto view the installable distribution names (subject to the output), thenwsl --install -d; fill inlabadminfor the user created at first startup. The host name defaults to the Windows host name, which can be set in the[network]section of/etc/wsl.conf.hostname = linuxlab. - systemd: WSL2 requires
[boot]systemd=truein/etc/wsl.confto use systemd as PID 1 (newer Ubuntu WSL distributions have it written by default); useps -p 1 -o comm=Check, the output should besystemd. Lesson 2 relies heavily on systemd. - Kernel and disk: WSL2 uses the kernel maintained by Microsoft (
uname -rwithmicrosoft-standard-WSL2). The system disk is a virtual VHDX and there is no real partitioning and boot process. Lesson 2's LVM switch to a loopback device can still be completed, but GRUB, boot failures, etc. (Lesson 7) cannot be practiced in WSL2. - The Windows file system is mounted at
/mnt/c, and the permission bits there are simulated: The permission experiments of module 3 must be done in Linux's own directory (such as~/linuxlab).
Initializing the working directory and tools
The following are executed in linuxlab with labadmin:
data-l="bash"
class="out" data-l="Expected output (example)"
acl provides getfacl/setfacl (module 3), strace is used to observe system calls (module 1), psmisc provides pstree/killall (module 5), and lsof is used for troubleshooting (module 8). These packages may have been pre-installed in the cloud image. apt will prompt "is already the newest version", which is normal.
Generate sample log (used in module 7)
data-l="bash"
class="out" data-l="Expected output (example)"
Optional: RHEL system comparison machine rhellab
Use only when you need to compare dnf, firewalld, and SELinux. Download 10.x DVD / Minimal ISO from rockylinux.org or almalinux.org to install in Hyper-V / VirtualBox: Hostname rhellab, create user labadmin and check "Make this user administrator" (that is, join the wheel group), 2 vCPU / 2 GB / 20 GB. Note EL10 requires an x86-64-v3 class CPU (AlmaLinux also provides an x86-64-v2 build). Multipass does not provide Rocky / Alma mirrors.
Environment self-check checklist
labadmin has sudo in the virtual machine, which is equivalent to root - the destructive operations in this lesson (changing permissions, deleting users, killing processes) should only be done in linuxlab . Do not copy them on work computers or production servers. Pause: multipass stop linuxlab; Snapshot: multipass snapshot linuxlab --name before-lesson1 (the instance must be in stopped state); Complete deletion: multipass delete linuxlab && multipass purge. Continue to use linuxlab in Lesson 2. Please do not delete it after completing this lesson. Module 1 · Linux Architecture: Kernel, User Space and Distribution
- Explain clearly the relationship between kernel, user space, system calls, processes, file descriptors, init (systemd), as well as the meaning and boundaries of "everything is a file".
- Tell us the whole process of executing a command: parsing and expansion → PATH search →
fork(clone) →execve→ kernel permission check and loading → system call →exit_group→ parent processwait4gets$?. - Distinguish the package format, package manager, release rhythm and support cycle of Debian/Ubuntu, RHEL series, Azure Linux, and Amazon Linux 2023, and know how to identify it on a strange machine within 10 seconds.
- Use
uname,/etc/os-release,/proc,straceto verify the above concepts on the lab VM.
What: What layers does Linux consist of
Strictly speaking, Linux is a kernel (Linus Torvalds Released in 1991, GPLv2). The "Linux system" we talk about every day is kernel + user space: C library (glibc), init system (systemd), Shell (bash), core tools (coreutils), package managers and thousands of applications. The one that selects, compiles, packages, tests, and maintains them for a long time is the release.
| Level | What is it | How to see it on linuxlab |
|---|---|---|
| Hardware/virtual hardware | CPU, memory, disk, network card; in the virtual machine, it consists of Hyper-V / KVM emulation | lscpu, lsblk, ip link |
| Kernel space | Run at CPU privilege level (x86 ring 0): process scheduling, memory management, virtual file system (VFS), network protocol stack, device driver, permission checking, namespaces / cgroups | uname -r, lsmod, /proc, /sys |
| System call interface | The only front door for user space to enter the kernel: openat, read, write, clone, execve, wait4, kill… About x86-64 400 | strace -c ls |
| C library glibc | packages system calls into functions such as open(), printf(); the dynamic linker ld-linux-x86-64.so.2 is responsible for loading shared libraries | ldd /usr/bin/bash |
| init: systemd(PID 1) | The first user space process started by the kernel, responsible for pulling up all services and recycling orphan processes (detailed in Lesson 2) | ps -p 1 -o pid,comm, systemctl --version |
| User space programs | bash, ls, sshd, python, myapp... all run at the non-privileged level (ring) 3), memory isolation from each other | ps -ef |
Why: Why separate kernel and user space
- Isolation and stability: The crash of the user program only affects itself (receiving SIGSEGV) and will not bring down the kernel; a kernel panic (kernel panic) is a complete machine failure.
- Security: Accessing the disk, network, and memory of other processes must go through system calls. The kernel checks the identity (UID/GID, capabilities) and permissions at the entrance - this is where the permission determination of module 3 occurs.
- Portable: the same
lsbinary, regardless of whether the underlying is NVMe or a network disk, VFS hides the difference behindopenat/read.
How: What happens when a command is executed (core animation of this module)
- Reading and parsing: bash reads a line and splits it into words and commands according to quotation marks, whitespace and operators (
|>&&). - Expansion: Curly brackets → tilde → Parameters and variables / Arithmetic / Command substitution → Word splitting → Pathname (wildcard) → Dequotation marks (detailed in Module 2).
- Command search: Aliases, functions, built-in commands (
cd,echo,type) are directly executed in the bash process; otherwise, check the hash table and press$PATHto find the executable file from left to right. - fork: bash calls
clone(glibc'sfork()) to copy the child process; copy-on-write makes it take almost no time. - Child process preparation: Perform redirection in the child process (
openat+dup2points fd 1 to the file), resume signal handling, and then callexecve. - Kernel: Permission checking and loading: Each directory on the path requires x (search) permissions, the file itself requires x permissions and the file system is not mounted with
noexec; read the ELF header (or find the interpreter with the#!line), map the code segment, and hand it over to the dynamic linker. On failure,execvereturnsENOENT/EACCES. - Run: The program reads and writes files and networks through system calls; each call will go through the kernel's permission check again.
- Exit and recycling: The program calls
exit_group(status), and the kernel sendsSIGCHLDto the parent process; bash gets the status inwait4and writes$?: 0 success, 1–125 program customization failure, 126 Found but unable to execute, 127 Command not found, 128+N terminated by signal N (Ctrl+C is 130). The child process is briefly in the zombie state (Z) before the parent process is recycled.
When: How to choose a distribution version
| Distribution | Family/Package Format | Package Manager | Current Version and Support (2026-11-17 Verification) | Typical Scenario |
|---|---|---|---|---|
| Ubuntu Server LTS | Debian-based / .deb | apt + dpkg | 26.04 LTS (2026-04) standard supported to 2031-05, ESM to 2036-05; 24.04 LTS standard supported to 2029-05; one LTS every two years, with 9 in between Month's transition version (latest 26.10) | The most common general-purpose Linux, Kubernetes nodes, development machines on the cloud |
| RHEL / Rocky / AlmaLinux | Red Hat system / .rpm | dnf (EL10 is dnf 4.20) + rpm | RHEL 10.3 (2026-11-11); Rocky 10.2, AlmaLinux 10.x; each major version has a life cycle of approximately 10 years, and minor versions approximately every 6 months | Enterprise, software that requires commercial support and certification (database, SAP) |
| Azure Linux | Microsoft maintenance / .rpm | 3.0 uses tdnf | 3.0 official version; 4.0 in Entering public preview in mid-2026 (if it has been GA, please refer to the official document) | AKS nodes, container hosting and thin workloads on Azure |
| Amazon Linux 2023 | Fedora-based AWS distribution / .rpm | dnf | Standard support to 2027-06-30, maintenance period until 2029-06-30; minor versions are released quarterly, each version corresponds to a new AMI and a locked warehouse version | EC2, ECS, Lambda and other AWS workloads (Lesson 4) |
You will also encounter: Debian (Ubuntu upstream), Fedora (the upstream direction of RHEL), SUSE / openSUSE (zypper), Alpine (apk, musl libc, common in container images). Selection principles: What the team is familiar with, what the supplier has certified, what the cloud platform defaults to, and whether the support cycle covers the system life.
Key changes in Ubuntu 26.04 LTS relative to 24.04 (relevant to this lesson)
| Components | 24.04 LTS | 26.04 LTS | How it affects you |
|---|---|---|---|
| Kernel (GA) | 6.8 | 7.0 | The version number jumps to 7, but the number is rolled, and the user space interface remains compatible |
| systemd | 255 | 259 (cgroup v1 removed) | Old container runtimes/monitoring agents that rely on cgroup v1 need to be upgraded |
| sudo | sudo(sudo.ws) | sudo-rs (original renamed sudo.ws) | The prompt changes to [sudo: authenticate] Password:; does not support I/O logs and sudoreplay, no sudo-ldap (module 4) |
| Core-Tools | GNU coreutils | rust-coreutils (uutils); cp/mv/rm/df/true Still GNU | The wording of individual options or error messages may be different; the GNU version is provided with the gnu prefix (such as gnuls) and can be switched as a whole (module 2) |
| APT | 2.7 | 3.1 (new solver, apt history-list, apt-key removed) | The apt-key add in the old tutorial no longer works, use Signed-By instead (module 6) |
| Python / OpenSSH | 3.12 / 9.6p1 | 3.14 / 10.2p1 | myapp's virtual environment uses 3.14; DSA keys are no longer supported |
| Time synchronization | systemd-timesyncd | chrony (new installation) | Time synchronization experiment for lesson 2 |
immutable attributes, etc. For example, execve a file without any x bits, root will also get Permission denied. ③ "cd is a program" - cd must be a Shell built-in command, because changing the working directory of the child process will not affect the parent process. ④ "The command cannot be found because it is not installed" - it may also be a different PATH (sudo Use secure_path), spelling error, or lack of x permissions (that is 126 instead of 127). ⑤ "Kernel version 7.0 means big changes" - The major version number of Linux only rolls after the minor version number becomes larger, which does not mean incompatibility. Architecture diagram: linuxlab layering
Flow chart: the lifeline of a command
Core Animation 1: The entire process of executing a command
Take the command entered by labadmin on linuxlab as an example. The upper half is user space (bash and subprocesses), and the lower half is the kernel; the right side shows the real system calls (simplified) that can be seen by strace -f, and the lower terminal shows the output seen by the user and $?. Switch scenes to see at which step the command failed and what the exit code was.
class="out" data-l="syscalls" id="a1q" style="min-height:200px;white-space:pre-wrap"
search_for_command) in the parent process, and then forks; even if the command cannot be found, bash will be called in the child process command_not_found_handle (Ubuntu command-not-found prompt) and exit with 127. The redirection is done in the child process, so the redirection in sudo ls > /etc/x is still done by your own bash to open the file as labadmin - this is the source of "sudo but Permission denied". execve 's permission checks follow path_resolution(7): every directory on the path requires search(x) permission; even if it has CAP_DAC_OVERRIDE, execution is only allowed if the file has at least one x bit. You can see these calls for yourself with strace -f -e trace=clone,execve,openat,wait4 bash -c '…' . Command table
| Command | Function | Key parameters/description |
|---|---|---|
uname -a / uname -r | Kernel name, version, architecture | -r only looks at the kernel version, -m looks at the architecture |
cat /etc/os-release | Distribution identity (all modern distributions have it) | ID, ID_LIKE, VERSION_ID, VERSION_CODENAME |
hostnamectl | Host name, OS, kernel, virtualization type | Show Virtualization: microsoft/kvm |
type / command -v | Determine whether a name is an alias, function, built-in, or external program | type -a ls List all candidates |
strace | Trace system calls | -f Trace child processes, -e trace= filtering, -c statistics |
ldd | View dynamically linked shared libraries | Only used for trusted binaries |
echo $? | Exit code of the previous command | It will be overwritten every time a command is executed |
pro status | Ubuntu Pro / ESM status (Ubuntu) | Free for up to 5 machines for individuals |
data-l="bash"
class="out" data-l="Expected output (example, 26.04 on Hyper-V)"
How to verify: Determine the distribution version in the script should read ID / ID_LIKE of /etc/os-release (ID="rocky", ID_LIKE="rhel centos fedora" for Rocky, ID="amzn" for Amazon Linux 2023), do not parse uname or /etc/issue. Common mistakes: Treating the kernel minor version number (such as -15-generic) as the release version. Production use: Asset inventory, patch baseline verification.
data-l="bash"
class="out" data-l="Expected output (example, excerpt)"
The number is different every time. The failure of openat in the errors column is usually caused by the dynamic linker trying multiple paths in sequence to find the library or language file, which is normal.
data-l="bash"
class="out" data-l="Expected output (example)"
Goal: Identify the system identity and see "fork → execve → wait4" with strace. Environment:linuxlab, labadmin. Fees: None.
data-l="bash"
class="out" data-l="Expected output (example)"
. /etc/os-release Use source to read the variables in the file into the current Shell - this file itself is a legal Shell variable assignment. /sbin/init is a symbolic link to systemd.
data-l="bash"
class="out" data-l="Expected output (example, PID different)"
Pay attention to four details: ① ~ has been expanded into /home/labadmin before execve; ② openat occurs in child process 4121, earlier execve; ③ The open mode 0666 will be filtered by umask (module 3); ④ echo done is a built-in command and does not generate clone/execve. On 26.04 /usr/bin/ls from rust-coreutils, the system call order is generally the same as the GNU version, details may differ slightly.
data-l="bash"
class="out" data-l="Expected output (example)"
cat /etc/os-release ID="rocky" or ID="almalinux", ID_LIKE="rhel centos fedora"; uname -r Shaped like 6.12.0-…el10…x86_64 (EL10 is based on the 6.12 LTS kernel and will be backported with patches in the long term). rm ~/linuxlab/tmp/trace.txt (retain deploy.sh, used by module 3). Case 1: "Permission denied even after sudo"
Problem: When the operation and maintenance script executes sudo echo "vm.swappiness=10" > /etc/sysctl.d/99-app.conf, Permission denied is reported. Root cause: The redirection causes the current user's Shell to open the file first in the child process after the fork, and sudo only elevates echo. Method:echo "vm.swappiness=10" | sudo tee /etc/sysctl.d/99-app.conf > /dev/null, or sudo sh -c '…'. Prevention: Make "sudo + redirection" a check item during code reviews.
Case 2: The distribution version is determined to be hard-coded, causing the script to fail on the new system
Problem: The installation script uses grep -q "CentOS" /etc/redhat-release to determine the RHEL system and goes to the wrong branch after switching to Rocky / AlmaLinux. Method: Read the ID and ID_LIKE of /etc/os-release, and press the "family" branch (*rhel*|*fedora* → dnf; *debian* → apt). Limitations: Amazon Linux 2023's ID_LIKE="fedora" is not completely consistent with the RHEL package name and needs to be tested separately.
Case 3: Audit issues caused by expiration of support cycle
Issue: The audit found that multiple servers are still running Ubuntu 20.04, standard support has ended in 2025-05, and security updates are only available through Ubuntu Pro (ESM). Method: Enable Pro for a short period of time to obtain ESM patches, and formulate a migration plan to 24.04 / 26.04; record the VERSION_ID and EOL date of each machine in the asset system. Prevention: For new projects, select the latest LTS and list "release EOL earlier than the system retirement date" as a blocking item in the architecture review.
Common errors and solutions
bash: xxx: command not found (exit code 127)
Cause: The command is spelled incorrectly, the software is not installed, the directory is not in $PATH, or PATH is replaced by secure_path under sudo.
data-l="bash"
Fix: Install the package, use an absolute path, or add the directory to PATH (write ~/.bashrc or ~/.profile).
bash: ./script.sh: Permission denied (exit code 126)
Cause: The file does not have the x bit; or the file system is mounted with noexec (such as /tmp in some systems); or a directory on the path lacks x permissions.
data-l="bash"
Fixed: chmod u+x script.sh; use bash script.sh to explicitly call the interpreter during noexec, or change to a directory that allows execution.
bash: ./tool: cannot execute: required file not found / No such file or directory (the file obviously exists)
Reason:execve returns ENOENT not the file itself, but the interpreter or dynamic linker it requires: the first line of the script #!/usr/bin/python points to a path that does not exist, or the file has a Windows newline (#!/bin/bash\r), or the binary was compiled for another architecture / musl.
data-l="bash"
Fixed: sed -i 's/\r$//' tool to remove CR; fix shebang to #!/usr/bin/env python3; use the correct architecture build.
Exec format error
Cause: The binary architecture does not match (running an arm64 program on x86-64), or the script is missing a shebang and is exec'd directly by a non-shell program.
data-l="bash"
Fix: Download the version corresponding to the architecture (x86_64/amd64 or aarch64/arm64); add #!/bin/bash to the first line of the script.
1. Use a command to output "release ID/version/kernel version", for example ubuntu 26.04 7.0.0-15-generic.
data-l="bash"
Use sub-shell brackets to avoid contaminating the current shell with os-release variables.
2. Prove that cd will not spawn new processes, but ls will.
data-l="bash"
Only see bash's own execve, a clone and an execve of /usr/bin/ls; cd and true (built-in) do not generate any clone/execve. Adding ; true at the end is to prevent bash from optimizing the last simple command of the -c string by "executing directly without fork".
A colleague ran backup.sh in cron. The manual execution was normal, but "aws: command not found" was reported in cron. Please analyze the cause and suggest two fixes.
The shell launched by cron does not read interactive configuration files, PATH usually only has /usr/bin:/bin, and the aws CLI is installed in /usr/local/bin or ~/.local/bin. Command lookup failed in PATH → 127. Fixes: ① Use absolute paths in scripts or export PATH=/usr/local/bin:/usr/bin:/bin at the beginning; ② Set PATH=… at the top of crontab. A better approach is to use systemd timer from Lesson 2 and declare the environment explicitly. When troubleshooting, add echo "$PATH" >> /tmp/backup-debug.log at the beginning of the script.
Verified teaching video
Official document
- execve(2) · fork(2) · syscalls(2) · os-release(5)
- Ubuntu 26.04 LTS release notes · Ubuntu release cycle
- kernel.org · AL2023 release cadence
Video storyboard script (about 90 seconds)
This courseware cannot directly generate video/MP3. Storyboards and explanation scripts have been provided, which can be generated by video tools.
Screen: A horizontal dotted line divides the screen into upper and lower halves, with "User Space" written above and "Kernel" written below.
Narration: The Linux system is divided into two halves, with the program living on top and the kernel living below. There is only one door in the middle, called the system call.
Screen: Entering in the terminal
ls -l *.log > list.txt, the words are cut and the asterisks become three file names. Narration: After pressing Enter, bash parses and expands first, and the tildes and asterisks have become real paths here.
Screen: bash copies a child process, the child process opens list.txt, and then enters the kernel through the dotted line. The kernel checks the x permission and then loads ls.
Narration: bash forks first, the child process handles the redirection, and then execves, the kernel checks permissions and loads the new program.
Screen: ls ends, number 0 flies back to bash, displayed
$? = 0; 126, 127, 130 listed next to it. Narration: The program exits, and the parent process uses wait to get the exit code. Remember: 126 cannot be executed, 127 cannot be found, 128 plus N is killed by a signal.
Module 2 · Shell and File System Hierarchy (FHS)
- Speak bash in order Expansion of: braces, tildes, parameters/variables, arithmetic, command substitution, word splitting, pathname expansion, dequotation, and the ability to predict the parameters that a command will ultimately pass to the program.
- Use single quotes, double quotes, and backslashes correctly; master the order rules of
<<<|and redirection. - Understand the differences between configuration files,
PATH, environment variables and Shell variables read by login shell and interactive shell. - Press FHS to tell the responsibilities of
/etc,/var,/usr,/opt,/srv,/run,/proc,/tmp, and know where each file of myapp should be placed.
What: Shell is
Shell is an ordinary user space program, responsible for reading commands → rewriting (expanding) → starting programs → collecting exit codes. The interactive default shells of Ubuntu and RHEL systems are both bash (5.3 in 26.04); Ubuntu's /bin/sh points to the smaller and faster dash, and RHEL's /bin/sh points to bash - so do not use bash-specific syntax (such as [[ ]], array).
Bash expansion order (bash manual "Shell Expansions")
| # | Expansion | Example | Result |
|---|---|---|---|
| 1 | Braces brace | mkdir -p app/{bin,etc,log} | Three parameters app/bin app/etc app/log |
| 2 | tilde tilde | ~/linuxlab, ~myapp | /home/labadmin/linuxlab, myapp's home directory |
| 3 | Parameters and variables, arithmetic, command substitution (from left to right) | $HOME, ${PORT:-5000}, $((2*3)), $(date +%F) | Values are substituted |
| 4 | Word splitting | Unquoted expansion results are split by $IFS (space, tab, newline) | f="my file"; ls $f → two parameters |
| 5 | Pathname pathname (glob) | *.log, ?, [0-9] | Replace with matching file name in alphabetical order; default to unchanged if no match |
| 6 | Quote removal | Remove unescaped \ ' " | The program cannot see the quotation marks |
| Quotation marks | Effect | When to use |
|---|---|---|
'Single quotation mark' | Complete literal, no expansion | awk program, sed expression, string containing $ |
"Double quotes" | Allow $variable, $( ), \, but prevent word splitting and wildcards | enclose all variables in double quotes by default: "$file" |
\ Backslash | Escapes the next character; \ at the end of the line indicates line continuation | Long command line break |
Redirection and pipe
| Writing | Meaning |
|---|---|
cmd > f / cmd >> f | Standard output (fd 1) overwrites/appends to f |
cmd 2> err.log | Standard error (fd 2) writes to file |
cmd > all.log 2>&1 | First point 1 to the file, then let 2 copy 1 → Both enter files. The order is reversed (2>&1 > f) when 2 still points to the terminal |
cmd &> all.log | bash abbreviation, equivalent to the previous line |
cmd < in.txt / <<'EOF' / <<< "str" | Read standard input from file / here-doc (quotation mark EOF means the content is not expanded) / here-string |
a | b / a |& b | a's stdout (/ plus stderr) is connected to b's stdin; both ends of the pipe are two processes running concurrently |
a && b / a || b / a ; b | a will be executed only if it succeeds b / a will be executed only if it fails b / unconditional sequential execution |
The exit code of the pipeline defaults to the exit code of the last command; set -o pipefail causes the pipeline to fail when any link fails (Lesson 5 Script Engineering). ${PIPESTATUS[@]} can view the exit code of each segment.
Shell configuration files and variables
- Login Shell (SSH login,
sudo -i,bash -l): read/etc/profile(and/etc/profile.d/*.sh), and then The first one that exists among~/.bash_profile,~/.bash_login, and~/.profile; Ubuntu's~/.profilewill then source~/.bashrc. - Interactive non-login Shell (open another bash in the terminal): read
/etc/bash.bashrc(Ubuntu) and~/.bashrc. Non-interactive (script, cron): Read neither. - Shell variables vs environment variables:
X=1is only in the current Shell; it will be inherited by the child process (envp of execve) afterexport X=1.envlooks at environment variables,setlooks at all. - PATH: colon separated, search from left to right. Ubuntu adds
~/.local/binand~/bin(when present) to PATH by default. Never put.in PATH.
FHS: Where the files are placed
| Directory | Responsibilities | Myapp used |
|---|---|---|
/usr/bin, /usr/sbin, /usr/lib | Programs and libraries installed by the distribution package (written only by the package manager). Both Ubuntu and RHEL have "usr merged": /bin → usr/bin, /lib → usr/lib is a symbolic link | /usr/bin/python3, /usr/bin/redis-server |
/usr/local | The local administrator manually compiles and installs the software (the package manager does not touch it) | — |
/opt | Self-contained third-party/add-on applications, /opt/ | /opt/myapp/app, /opt/myapp/venv |
/etc | Native configuration (text file), not the program | /etc/myapp/myapp.env |
/var/lib | Persistent state data of the program | /var/lib/redis |
/var/log | Journald's persistent log in /var/log/journal) | Lesson 2 Switch to journald |
/var/cache, /var/tmp | Rebuildable cache; temporary file retained across reboots | /var/cache/apt/archives |
/tmp | Temporary file, writable by everyone (sticky bit, module 3), probably tmpfs, cleared upon restart | — |
/run | Runtime data (PID file, socket), tmpfs, rebuild at boot | /run/redis |
/srv | Service data provided by the local machine (site, FTP, share) | Module 3 /srv/share |
/home, /root | Normal user home directory, root's home directory | /home/labadmin/linuxlab |
/proc, /sys, /dev | Virtual file system exported by the kernel: process information, device and kernel parameters, device nodes | /proc/ (module 5) |
/boot, /mnt, /media | Kernel and boot files; temporary mount points; removable media | Lesson 2 Mounting |
When: What to pay attention to when using rust-coreutils in Ubuntu 26.04
26.04 ls, cat, chmod, sort, etc. come from uutils (rust-coreutils) and aim to be compatible with GNU behavior, but individual unpopular options, error message wording, and performance characteristics may be different. When encountering differences in script behavior: first use ls --version to confirm the implementation; the GNU version is provided with the gnu prefix (such as gnuls); you can also switch as a whole according to the Ubuntu documentation: sudo apt install coreutils-from-gnu coreutils-from-uutils- --allow-remove-essential (reverse switching reverses the two package names). Don't use update-alternatives to switch coreutils.
rm *.log It's rm looking for files" - it's bash expanded *, rm only receives a list of file names; file names starting with - will be treated as options and should be written as rm -- *.log or rm ./*.log. ② "Nothing is expanded in double quotes" - $VAR and $( ) in double quotes are still expanded, only splitting and wildcarding are prevented. ③ "cmd 2>&1 > f Equals cmd > f 2>&1" - redirection is executed from left to right, and the results are different in different orders. ④ "PATH is set in ~/.bashrc , which can also be seen by cron and systemd" - non-interactive environments do not read it. ⑤ "Things in /tmp will always be there" - it may be cleaned up during restart or by systemd-tmpfiles regularly. FHS map: key directories on linuxlab
File descriptors and redirections
cmd | grep error Often "nothing is caught", write cmd 2>&1 | grep errorShell expansion step-by-step demonstration
Select a command and see step by step how bash turns the text you enter into the parameter array (argv) passed to execve. Assume that the current directory ~/linuxlab/logs contains access.log, app 1.log (including spaces), error.log, HOME=/home/labadmin, f="app 1.log".
class="out" data-l="words" id="a2words" style="min-height:160px;white-space:pre-wrap"
set -x in bash and then run the command. Bash will print out the expanded results starting with + before execution; set +x Close. You can also use printf '[%s]\n' args… to view the boundaries of each parameter. Command table
| Command | Function | Key points |
|---|---|---|
pwd / cd - / cd | Current directory / return to the previous directory / home directory | pwd -P Display the physical path after parsing the symbolic link |
ls -lah / tree -L 2 | Column directory (including hidden files, human-readable size)/tree | ls -ld dir Look at the directory itself |
cp -a / mv / rm -r / mkdir -p | Copy (keep attributes)/move/recursively delete/recursively create directory | rm -ri Interactive confirmation; no recycle bin |
ln -s target link name | Symbolic link | Hard link ln cannot cross file systems and cannot link directories |
cat / less / head -n / tail -f | View files | less in / search, G to the end, q exit |
find | Search by name, time, size, owner | find /var/log -name '*.gz' -mtime +7 -size +1M |
stat / file | inode metadata / file type | stat -c '%A %U:%G %s %n' f |
man / --help / help | Manual / program help / bash built-in help | man 5 passwd Specify the chapter; man -k keyword |
history / Ctrl+R | History command/reverse search | !! Previous article, sudo !! Use sudo to rerun |
env / export / printenv PATH | Environment variable | VAR=x cmd only takes effect on this command |
data-l="bash"
class="out" data-l="Expected Output"
How to verify: The result of wildcard expansion will not be split by words again, so app 1.log in demo/log/* is still a parameter; and the unquoted one $f will be torn down. Common mistakes: In the script, for f in $(ls) encounters an error in the file name with spaces. You should write for f in ./*.
data-l="bash"
class="out" data-l="Expected Output (Example)"
The error message of the second command is printed directly on the terminal (fd 2 still points to the terminal when 2>&1), without entering out2.txt.
data-l="bash"
class="out" data-l="Expected Output (Example, 26.04)"
Goal: Establish the experimental structure of ~/linuxlab and master expansion, redirection and PATH. Environment:linuxlab, labadmin. Fees: None.
data-l="bash"
class="out" data-l="Expected Output (Example)"
If there is no section in ~/.profile (for example, RHEL system), add export PATH="$HOME/.local/bin:$PATH" at the end of ~/.bashrc.
data-l="bash"
class="out" data-l="Expected Output"
data-l="bash"
class="out" data-l="Expected Output (Example)"
These Permission denied are the permission checks discussed in module 3: labadmin does not have r or x permissions on these directories.
data-l="bash"
class="out" data-l="Expected Output (Example)"
Whether /tmp is tmpfs depends on the distribution and version; when the file system of df -h /tmp is listed as tmpfs, it will be cleared after restarting.
rm -r ~/linuxlab/demo ~/linuxlab/out1.txt ~/linuxlab/out2.txt 2>/dev/null (retain tmp directory and PATH settings). Case 1: An empty variable deleted the entire directory
Problem: Cleanup script rm -rf $BUILD_DIR/, one time BUILD_DIR was not set, and after expansion it became rm -rf / (modern rm default --preserve-root rejects the root directory, but the similar writing method rm -rf $DIR/* will delete everything that can be deleted under /*). Method: Use "${BUILD_DIR:?BUILD_DIR not set}". When the variable is empty, it will directly report an error and exit; add double quotes to all variables; start the script with set -u. Prevention: Running ShellCheck in CI (Lesson 5).
Case 2: The log "disappeared"
Problem: When the startup script is written app 2>&1 > /var/log/app.log, the error message is not entered into the log file, and there is no way to troubleshoot the failure. Method: Change to > /var/log/app.log 2>&1; a better approach is to leave it to systemd/journald for unified collection (Lesson 2).
Case 3: The files under /usr were manually modified and overwritten after the upgrade
Problem:Operation and maintenance directly modify /usr/lib/systemd/system/redis-server.service to adjust parameters, and all changes will be lost after the next apt upgrade. How to: The package manager owns /usr; native customizations should be placed in /etc (systemd uses systemctl edit to generate drop-ins, Lesson 2). Restrictions: dpkg only protects files registered as conffile under /etc. When upgrading, it will ask how to merge.
Common errors and solutions
rm: invalid option -- 'r' / Files whose file names start with - cannot be deleted
Reason: Wildcard expansion produces file names such as -rf.txt, which are treated as options by the program.
data-l="bash"
bash: syntax error near unexpected token `(' / unexpected EOF while looking for matching `"'
Cause: The quotes are not paired, or bash syntax is used in sh (dash).
data-l="bash"
-bash: /usr/bin/ls: Argument list too long
Cause: The total length of parameters expanded by wildcard expansion exceeds the kernel's ARG_MAX limit (execve returns E2BIG).
data-l="bash"
Changed ~/.bashrc but it does not take effect in SSH login / cron / systemd
Reason: The login shell reads ~/.profile (in Ubuntu it reads ~/.bashrc again, but only when interacting); cron and systemd These files are not read at all.
data-l="bash"
Fix: Place environment variables in the service's own configuration (systemd's Environment= / EnvironmentFile=, Lesson 2).
1. Create ~/linuxlab/proj/{src,test,docs} at once, and create README.md in each subdirectory.
data-l="bash"
2. Run find / -name sshd_config, keeping only normal results and discarding all errors.
data-l="bash"
The deployment script contains cp $SRC/*.conf $DEST. The file was copied to the wrong location on one machine, and another machine reported "cp: target 'x' is not a directory". What could be the reason? How to change it?
Unquoted variables will be split by words: if DEST contains spaces (such as /srv/my app), it will be split into two parameters, and the last parameter will be regarded as the target; when SRC is empty, the glob will become /*.conf, copied from the root directory. Fix: cp -- "${SRC:?}"/*.conf "${DEST:?}/"; use [ -d "$DEST" ] to precheck; enable set -euo pipefail and ShellCheck.
Verified teaching video
Official documentation
- Bash Reference Manual: Shell Expansions · Redirections · Bash Startup Files
- Filesystem Hierarchy Standard 3.0 · hier(7)
- Ubuntu Server: System utility replacements(rust-coreutils / sudo-rs)
Video storyboard script (about 75 seconds)
This courseware cannot directly generate videos/MP3s. Storyboards and explanation scripts have been provided, which can be generated by video tools.
Screen: Input
rm $f, $f becomes "app 1.log", and then is cut by scissors into two cards: "app" and "1.log". Narration: Variables without quotation marks will be split, and rm receives two file names.
Screen: Six gates light up in sequence: braces, tildes, variables, splits, wildcards, and dequotes.
Narration: bash is expanded in a fixed order before execution, and what is finally passed to the program is just a set of strings.
Screen: The root directory tree is expanded, /etc, /var, /opt, /usr are highlighted in sequence, and the myapp file appears next to it.
Narration: The program is in usr or opt, the configuration is in etc, and the changing data is in var. This is FHS.
Module 3 · Files, permissions, ownership and ACLs
- Understand each column of
ls -l: file type, 9 permission bits, special bits,+(ACL), number of links, owner, group. - Explain the different meanings of r / w / x to file and directory (x of directory = can be entered/traversed, w = can be created, deleted and renamed).
- Use
chmod(symbol and octal),chown,chgrp,umaskto set permissions; understand the roles and risks of SUID, SGID, and sticky. - Use
setfacl/getfaclto authorize a single user or group, set the default ACL, and understand how mask limits effective permissions. - Deduce the result of an access according to the real algorithm of the kernel: capabilities → owner → named user → group → others (core animation 2 of this lesson).
What: ls -l of each column
class="out" data-l="ls -l interpretation"
| bits | For files | For directories |
|---|---|---|
| r(4) | Read content | List the file names in the directory (ls) |
| w(2) | Modify the content (deleting files looks at directory w) | Create, delete, and rename entries in the directory (x is also required) |
| x(1) | Execute as a program | Enter/traverse the directory (cd, prerequisite for accessing files in it) |
SUID (4000, s is in owner x position) | The effective UID of the process becomes the file owner during execution (such as /usr/bin/passwd) | Not meaningful on Linux |
SGID (2000, s is in the x position of the group) | The effective GID during execution becomes the file's group | The group of the new file inheritance directory (required for shared directories) |
sticky (1000, t is in the other x positions) | meaningless | Only the file owner, directory owner or root can delete/rename the file (/tmp is 1777) |
Uppercase S/T means that the special bit is set but the corresponding x bit is not set. The kernel ignores SUID/SGID on scripts (#!) for security reasons.
Why: Where does the permission check occur
Permissions are not checked by ls or bash, but by the kernel at the system call entry (openat, execve, unlinkat, mkdirat...). Check the using process's file system UID (fsuid, usually equal to the effective UID), effective GID, and additional groups, plus the process's capabilities. The LSM (AppArmor for Ubuntu, SELinux for RHEL) can then deny it again (Lesson 6).
How: Kernel decision algorithm (acl(5), path_resolution(7))
- Path resolution: Search step by step starting from
/, each directory passed requires x (search) permission, otherwiseEACCESis returned - even if the target file itself is 777. - capabilities:
CAP_DAC_OVERRIDEbypasses read and write execution checks (but execution requires the file to have at least an x bit);CAP_DAC_READ_SEARCHonly bypasses read and directory searches. root has all capabilities by default. - Owner: The effective UID is equal to the file owner → only look at the owner bit (
user::), the match is final, and no longer look at the group and others. - Named user ACL (
user:bob:rw-): UID matching → The entry is determined after intersection with mask. - Group: Valid GID or any additional group matching file belongs to the group (
group::) or named group entry (group:ops:r--) → any matching entry (after intersection with mask) contains the required permissions and is allowed, otherwise rejected and will not look at other again. - Other (
other::): Used when none of the above match.
When there is no extended ACL, step 4 does not exist and mask does not participate. It is the classic "owner → group → other, the first match is the final result".
umask: default permissions for new files
The program requests a mode when creating the file (usually 0666 for the file, 0777 for the directory), and the kernel then removes the bits in the umask: 0666 & ~0022 = 0644, 0777 & ~0022 = 0755. umask only removes permissions, never adds x. UMASK 022 in Ubuntu's /etc/login.defs, combined with USERGROUPS_ENAB yes and pam_umask, will relax the group bit to be consistent with the owner (the common result is 0002) for ordinary users whose "username has the same name as the main group and UID=GID"; root is 0022. Subject to the actual output of the umask command. The Default ACL on the directory overrides the group/other parts of the umask.
When: Which mechanism to choose
| Requirements | Recommended practices |
|---|---|
| A team shared directory | Build a group + directory 2770 (SGID) + members join the group; add default ACL or adjust umask when new file group is required to be writable |
| Give "an additional person/group" read-only | ACL: setfacl -m u:bob:rX, instead of putting other Open |
| Multiple people can write but cannot delete other people's files | sticky bit (chmod +t) |
| The program needs to bind <1024 port or capture packets | capabilities (setcap cap_net_bind_service=+ep, or systemd's AmbientCapabilities=, Lesson 2) instead of SUID root |
| Secret configuration of the service | root:myapp 0640: Root can be changed, the service is read-only and not visible to others |
chmod 0077 f ② "chmod 777 can solve the problem" - it just hides the problem and creates security holes; first use namei -l to find out which level lacks permissions. ③ "Deleting files requires the w permission of the file" - what is required is w+x of the directory is located (and the owner if sticky). ④ "If rw is given to setfacl, it will definitely be able to write" - it also depends on the mask; later execution where chmod g-w will change the mask together. ⑤ "It will take effect immediately after joining the group" - the group list is determined when logging in. If there is an existing session, you need to log in again or newgrp(module 4). Permission determination flow chart
Design of shared directory /srv/share
Core Animation 2: Permission determination
Object: Directory /srv/share (root:devs 2770, ACL user:bob:r-x, group:ops:r-x) and file report.txt (alice:devs, ACL user::rw-, user:bob:rw-, group::r--, group:ops:r--, mask::r--, other::---). Choose "who" and "what" and decide step by step in the order of the core.
class="out" data-l="acl" id="a3acl" style="min-height:170px;white-space:pre-wrap"
chmod / umask calculator
| r | w | x | Special bit | |
|---|---|---|---|---|
| user | ||||
| group | ||||
| other |
class="out" data-l="Results" id="a3calcout"
Command list
| Command | Function | Example |
|---|---|---|
chmod | Change permissions (symbol or octal) | chmod u+x,go-w f, chmod 640 f, chmod -R g+rX dir (big X: only add x to directories and files that already have x) |
chown / chgrp | Change the owner/group (root is required to change the owner) | sudo chown -R myapp:myapp /var/lib/myapp |
umask | View/set the umask of the current shell | umask -S symbol display |
getfacl / setfacl | View/set the ACL | setfacl -m u:bob:rX f, -x delete entry, -b delete all, -d default ACL, -R recursive |
namei -l path | Display the permissions of each component on the path step by step | Find "Which level is missing x" |
stat | Octal mode, inode, timestamp | stat -c '%a %A %U:%G %n' f |
getcap / setcap | File capabilities | getcap -r /usr/bin 2>/dev/null |
lsattr / chattr | File system attributes (immutable i. Append only a) | sudo chattr +i /etc/resolv.conf (use with caution) |
find -perm | Find by permissions | sudo find / -xdev -perm -4000 -type f List SUID File |
data-l="bash"
class="out" data-l="Expected output (example, Ubuntu regular user)"
How to verify: When the umask is 0002, the new file is 664 and the directory is 775; when it is 0022, it is 644 / 755. The s of /usr/bin/passwd allows ordinary users to modify the own line in /etc/shadow as root (the passwd program does an identity check internally). Common mistakes:chmod -R 755 adds x to all files.
data-l="bash"
class="out" data-l="Expected output (example)"
systemd uses ACLs to allow members of the adm group (the first user created during Ubuntu installation) to read the journal without sudo - ACLs can be found everywhere in distributions. The specific entries are subject to your system.
Goal: Create a shared directory /srv/share: devs group is read-write, bob is read-only, and others are not visible; verify SGID, default ACL, mask and sticky. Environment:linuxlab, labadmin (requires sudo). Users alice, bob, carol and group devs will be discussed in detail in module 4. Let’s quickly create them here. Fees: None.
data-l="bash"
class="out" data-l="Expected output (example)"
data-l="bash"
class="out" data-l="Expected output (example)"
The capital X in rX takes effect as x for the directory. default:user:: not specified in the default ACL is copied from the access ACL, default:mask:: is automatically calculated by setfacl as the union of group class entries (rw- ∪ r-- = rw-). labadmin is not in the devs group and is not the owner, so ordinary getfacl will fail due to the lack of x and requires sudo - this is a permission determination in itself.
data-l="bash"
class="out" data-l="Expected output (example)"
Although alice's umask is 0022, the new file is still group-writable: when the directory has a default ACL, the umask does not participate, and the group permissions come from the default ACL. The owned group is devs instead of alice's primary group. This is the effect of SGID.
data-l="bash"
class="out" data-l="Expected Output (Example)"
data-l="bash"
class="out" data-l="Expected Output (Example)"
Uppercase T: sticky is set but other has no x. The list of SUID files should be regularly compared to the baseline, and the presence of unfamiliar files is a sign of an intrusion (Lesson 6). sudo itself is also SUID root (sudo-rs on 26.04).
/srv/share, alice/bob/carol/eve and devs, module 4 continues to be used. Case 1: SSH key login suddenly fails
Problem: After someone executes chmod -R 775 /home/deploy, the deploy user cannot log in with the key, and the log Authentication refused: bad ownership or modes for directory /home/deploy. Root cause: sshd's StrictModes requires that the home directory, ~/.ssh, and authorized_keys cannot be written by others. How to:chmod 755 ~ ; chmod 700 ~/.ssh ; chmod 600 ~/.ssh/authorized_keys (Lecture 2 SSH module is explained in detail).
Case 2: Web service 403, chmod 777 is useless
Problem:nginx reads /home/alice/site/index.html and returns 403. The team changed the file to 777 but it still doesn't work. Root cause: The path /home/alice is 750, and the nginx process user (www-data) cannot traverse without x. Method: Do not put the site in the home directory, move it to /srv/www; or use minimum authorization setfacl -m u:www-data:x /home/alice. Tools:sudo -u www-data namei -l /home/alice/site/index.html.
Case 3: Confidential file read by everyone
Issue: Security scan found /etc/myapp/myapp.env permission 644, containing Redis password. How to:root:myapp 0640; Directory /etc/myapp is 0750 root:myapp; Pin these permissions in Configuration Management (Lesson 5 / Ansible Lesson). Prevention: Check find /etc -perm -o+r -name '*.env' during readiness review.
Common errors and solutions
Permission denied (file permissions appear to be OK)
Troubleshooting order:① x at each level on the path; ② Who am I (id, whether the group has taken effect); ③ ACL and mask; ④ mount options; ⑤ AppArmor / SELinux.
data-l="bash"
rm: cannot remove 'x': Operation not permitted (sudo does not work either)
Reason: The file has immutable attribute i or only appends a; or it is located in the sticky directory and you are not the owner (when not root).
data-l="bash"
setfacl: Operation not supported
Cause: The file system does not support ACL (such as some network or FAT file systems, WSL's /mnt/c). ext4/xfs/btrfs are supported by default.
data-l="bash"
chown: changing ownership of 'x': Operation not permitted
Reason: Only the process (root) that owns CAP_CHOWN can modify the owner; ordinary users can only chgrp their own files to the group to which they belong.
data-l="bash"
1. Let the directory /srv/reports belong to the group devs, the group can read and write, new files automatically belong to devs, others have no permission, and let the group ops read-only (including new files in the future).
data-l="bash"
2. Find ordinary files under /etc that others can write to.
data-l="bash"
File -rw----r-- 1 alice devs app.conf: Can alice read it? Can carol (devs member) read it? Can eve (other people) read it? Why?
alice can read (owner bit rw-). carol cannot read: She matches the group devs, and the group position is ---. The judgment ends at the group level and will not fall back to other. eve can read (other bit r--). This shows that Unix permissions are not "take the maximum value", but "the first matching category wins".
Verified teaching video
Official document
- acl(5): ACCESS CHECK ALGORITHM · path_resolution(7) · capabilities(7)
- chmod(1) · umask(2) · login.defs(5)
Video storyboard script (about 90 seconds)
This courseware cannot directly generate video/MP3. Storyboards and explanation scripts have been provided, which can be generated by video tools.
Screen:
-rw-r-----+ is split into five sections, each section is highlighted and its meaning is marked. Narration: The first one is the type, and then the three groups of rwx are for the owner, the group, and others respectively. The plus sign indicates that there is also ACL.
Screen: A process card "bob" starts from the door and passes through the three doors /, /srv, /srv/share in sequence, and checks x at each door.
Narration: Each level of directory on the path must have execution permission. If this step fails, there is no need to look at the following ones.
Screen: Determination ladder: root? Owner? Named user? Group? other? bob stops at "named user" and his rw intersects with mask r leaving only r.
Narration: The first matching category gives the conclusion; entries naming users and groups also intersect with the mask.
Screen: A new file is born, 0666 minus umask 0022 becomes 0644; the SGID directory next to it makes the group become devs.
Narration: umask determines the default permissions for new files, and SGID makes files in the shared directory belong to the team.
Module 4 · Users, groups and sudo
- Read Fields of
/etc/passwd,/etc/shadow, and/etc/group; distinguish ordinary users, system users (service accounts) and root. - Use
useradd/adduser,usermod -aG,passwd,chage,userdelto manage user life cycle; know when group membership changes take effect. - Write secure sudo rules (
/etc/sudoers.d/+visudo), understand%sudo/%wheel,NOPASSWD, command whitelist,secure_pathand logs. - Learn about the differences between Ubuntu 26.04's default sudo-rs and traditional sudo (
sudo.ws), and how to switch.
What: Account Database
| File | Format (colon separated) | Permissions |
|---|---|---|
/etc/passwd | name:x:UID:GID:GECOS:home:shell, x means the password is in shadow | 644 root:root (readable by everyone) |
/etc/shadow | name:hash:last modified:min:max:warning:grace:expiry:; hash in $y$ (yescrypt) or Starting with $6$ (SHA-512); ! or * means locked/unavailable password login | 640 root:shadow(Ubuntu)/ 000(RHEL) |
/etc/group | group:x:GID: member 1, member 2 (only additional members are listed here, the main group is in the GID field of passwd) | 644 |
/etc/login.defs | UID/GID range, umask, password validity period default value | 644 |
| Type | UID range (Ubuntu / RHEL default) | Features | Example |
|---|---|---|---|
| root | 0 | Has full capabilities; prohibiting direct SSH logins is a common baseline | root |
| System user | 1–999(SYS_UID_MIN–SYS_UID_MAX) | Run services, no password, usually no login Shell (/usr/sbin/nologin) | redis, sshd, myapp |
| Normal user | ≥ 1000(UID_MIN) | Human account, with home directory and Shell | labadmin, alice |
Other sources: Users may also come from LDAP / Entra ID / SSSD (Lesson 3 Entra ID login). getent passwd alice will query all sources through NSS, which is more reliable than grep /etc/passwd.
Why: Why do services need dedicated system users
- Minimum permissions: When myapp is compromised, the attacker only gets the permissions of the myapp user and cannot read
/etc/shadowor change the code in/opt/myapp/app(the owner is root). - Auditable:
ps -u myapp,ss -ltnp, and the UID in the log can directly correspond to the service. - Cannot log in: The shell is
nologin, the password field is!, and cannot be entered through SSH orsu(root can stillsudo -u myapp).
How: Workflow for sudo
/usr/bin/sudois SUID root Program: labadmin When you execute it, the effective UID of the process becomes 0 (special bit for module 3).- Read the files in
/etc/sudoersand@includedir /etc/sudoers.d, and match the rules according to the "user/group host=(target user:target group) command". The last matching rule takes effect. - Verify the caller's own password (not the root password) through PAM when necessary. After success, write the timestamp. By default, the same terminal will not ask again within 15 minutes.
- Record logs (syslog/journald: who, in which terminal, in whose identity, what was executed).
- Reset the environment (
env_reset), set PATH tosecure_path, switch to the target user's UID/GID/attachment group, thenexecvethe target command; the exit code is returned unchanged.
sudoers rule syntax
class="out" data-l="sudoers example"
- The command must write an absolute path; if parameters are written, only these parameters are allowed. If no parameters are written, any parameters are allowed.
- Dangerous whitelist:
vi,less,find,tar,python,bash,systemctl edit,apt install, etc. can "escape" into root shell - giving them is equivalent to giving ALL. - File names in
/etc/sudoers.d/containing.or ending with~will be ignored (sudoers(5)), so use90-devsinstead ofdevs.conf; the permissions should be0440.
Differences between sudo-rs (Ubuntu 26.04 default) and traditional sudo
| Aspects | sudo.ws (24.04 default) | sudo-rs (26.04 Default) |
|---|---|---|
| Implementation | C, with a long history and comprehensive functions | Rust rewritten, aiming for memory safety and simplicity |
| Password prompt | [sudo] password for labadmin: | [sudo: authenticate] Password: (per PAM prompt) - expect scripts matching old prompts will timeout |
I/O logs and sudoreplay | Supported | Not supported (sudo_logsrvd etc. are not provided) |
| LDAP sudoers | sudo-ldap | Not supported, use PAM/SSSD instead |
| sudoers syntax | Complete | Supports common subsets; use man sudoers-rs to view supported settings, sudo - help The name can still be called directly |
| Switch | sudo update-alternatives --config sudo (interactive) or sudo update-alternatives --set sudo /usr/bin/sudo.ws; the original version can still be called directly with the name of sudo.ws | |
When: su, sudo, sudo -i how to choose
| Command | Whose password is needed | Environment | Suggestion |
|---|---|---|---|
sudo cmd | Own | Reset, PATH=secure_path | Preferred: single command, leaving audit records |
sudo -i | Own | Simulate root login Shell | When multiple consecutive root operations are required |
sudo -u myapp cmd | Your own | As myapp identity | Verify the permissions of the service account (used extensively in this lesson) |
su - | root of(Ubuntu default root has no password → not available) | Root login Shell | Not recommended: shared root password cannot be traced back to people |
usermod -G devs alice Add alice to devs" - without -a , her additional group will be replaced with only devs, which may kick the administrator out of the sudo group. ② "Joining the group takes effect immediately" - the group list is determined by initgroups when logging in. Existing sessions need to be logged in again (or newgrp devs open a new Shell) ③ "It's okay to directly vim /etc/sudoers" - syntax errors will invalidate all sudo; visudo will be checked before saving ④. "NOPASSWD is just a convenience" - it allows anyone who gets the user's session (or a malicious script) to become root directly. ⑤ "Just delete the user" - to deal with the home directory, cron, files belonging to the UID (find / -uid) and SSH keys. What a user looks like in each file
chage -l will be converted to datesudo authorization path
sudo authorization process
Select a scenario and gradually observe how sudo matches rules, authentication, recording and execution. Rules: %sudo ALL=(ALL:ALL) ALL (Ubuntu default) added experimentally with this module /etc/sudoers.d/90-devs: %devs ALL=(root) NOPASSWD: /usr/bin/systemctl restart ssh.service, /usr/bin/systemctl status ssh.service.
/etc/sudoers (permissions 0440 root:root) and switch identities; authentication through PAM sudo Service configuration (/etc/pam.d/sudo) is completed; finally use setresuid/setresgid/setgroups to switch to the target identity execve. The wording of the rejection message is different between sudo.ws and sudo-rs (marked in the animation). When troubleshooting, refer to the log. Command table
| Command | Function | Key points |
|---|---|---|
id [user] / groups / whoami | View identity and group | id Display the group of current process, id alice Display group in database |
getent passwd|group|shadow name | Query account via NSS | Contains LDAP / SSSD users |
useradd -m -s /bin/bash u | Create user (underlying tool, common to all distributions) | -r system user, -d home directory, -M do not create a home directory, -G additional group |
adduser u | Debian/Ubuntu The interactive package (link to useradd on RHEL) | will prompt to set password and GECOS |
usermod -aG g u | Append additional group | Be sure to bring -a; -L/-U Lock/unlock, -s Change Shell, -e Expiration date |
gpasswd -d u g | Remove user from group | Also deluser u g (Ubuntu) |
passwd / chage | Set password / Password validity period | passwd -S u status, chage -l u, chage -d 0 u Force password change at next login |
userdel -r u | Delete user, home directory and mail | First pkill -u u; after find / -xdev -nouser |
visudo / visudo -f file / visudo -c | Safe editing/inspection sudoers | EDITOR=nano sudo visudo -f /etc/sudoers.d/90-devs |
sudo -l / sudo -l -U u | List your own/a user's sudo permissions | The first step in troubleshooting |
sudo -k / sudo -v | Clear/refresh the authentication timestamp | First -k |
last / lastlog / who / w | Login record and current session | lastlog has been replaced by lastlog2 on some systems |
data-l="bash"
class="out" data-l="Expected output (example)"
The output format of sudo -l is slightly different between sudo-rs and sudo.ws. The hash prefix $y$ means yescrypt (the default algorithm on Ubuntu and EL10).
data-l="bash"
class="out" data-l="Expected output (example, 26.04)"
The installation path and version number of sudo-rs are taken as an example, based on the output of readlink and --version on your system; on 24.04, readlink outputs /usr/bin/sudo, and the version is "Sudo version 1.9.x".
Goal: Complete the user life cycle: create dave (ops group), grant restricted sudo to the devs group, lock and delete eve; verify the effective timing of group membership. Environment:linuxlab, labadmin; alice/bob/carol/eve/devs created by module 3. Fees: None.
data-l="bash"
class="out" data-l="Expected output (example)"
data-l="bash"
Write the following content and save:
data-l="sudoers"
data-l="bash"
class="out" data-l="Expected output (example)"
If visudo is not on your system (depending on the sudo provider), first confirm with command -v visudo; do not fall back to direct editing.
data-l="bash"
class="out" data-l="Expected output (example)"
-n (non-interactive) allows sudo to fail directly when a password is required instead of prompting - suitable for scripts and testing. Commands that are not in the whitelist have no NOPASSWD rule to match, so the password is required first (and will be rejected once entered). The error wording depends on your sudo implementation.
data-l="bash"
class="out" data-l="Expected output (example)"
data-l="bash"
class="out" data-l="Expected output (example)"
Only passwd -l locking the password does not prevent SSH key login; also set expiration (-e 1) or change the shell to nologin Only reliable.
90-devs (module 8 readiness review checks them). Case 1: A usermod locked the administrator out
Problem: In order to allow the ops user to read the log, usermod -G adm ops was executed (missing -a), and ops was moved out of sudo group; there are no other administrator accounts at the time, and the rights cannot be escalated after the next login. How to: Restore via Cloud Serial Console/Single User Mode (Lessons 3, 4, 7). Prevention: Always -aG; retain at least two administrator identities; hand over accounts and groups to configuration management (Ansible lesson).
Case 2: less in the whitelist becomes root Shell
Problem: In order to allow the on-duty personnel to view the log, sudoers wrote NOPASSWD: /usr/bin/less /var/log/*; enter !bash in less to get root Shell, and wildcards also allow /var/log/../../etc/shadow. Method: Instead, add the on-duty personnel to the adm group to read the log directly (or systemd-journal group) without sudo. Principle: Do not use sudo if it can be solved with group permissions/ACL; when you must use sudo, only list specific commands and parameters that will not spawn a shell, or use sudoedit to edit files.
Case 3: The cron of the resigned employee is still running
Problem: After the account is deleted, its crontab is "resurrected" because the UID is reassigned to the new employee and runs as the new employee. How to: Offboarding process: Lock → Export data → crontab -r -u → userdel -r → find / -uid OLD Clean up legacy files; centralize identity (Entra ID / LDAP) to avoid UID reuse (Lesson 3).
Common errors and solutions
bob is not in the sudoers file. / I'm sorry bob. I'm afraid I can't do that
Cause: The user does not have any matching sudoers rules (the first sentence is the wording of sudo.ws, the second sentence is the wording example of sudo-rs), or has just joined the sudo group but has not logged in again.
data-l="bash"
Fix: sudo usermod -aG sudo bob to let bob log in again; or add minimal rules in sudoers.d.
>>> /etc/sudoers.d/90-devs: syntax error near line 2 <<<
Reason: The rule syntax is incorrect (missing comma, the command does not write an absolute path, and there is a space after the line continuation character). visudo will ask "What now?": Press e to re-edit, don't choose to force save.
data-l="bash"
If sudo is broken: Available on Ubuntu with pkexec visudo (requires polkit authentication), or via console/rescue mode fix.
The rules in sudoers.d do not take effect (visudo -c also passes)
Reason: The file name contains . (such as devs.conf) or ends with ~ end and is ignored; or is overridden by another rule (the last match takes effect).
data-l="bash"
This account is currently not available.
Cause: The user's shell is /usr/sbin/nologin (normal configuration for system users).
data-l="bash"
1. Create system user backup: no home directory, no login, main group with the same name.
data-l="bash"
2. List all common usernames with UID ≥ 1000 and their shells.
data-l="bash"
The development team hopes to "deploy myapp": copy the new code to /opt/myapp/app and restart the service. Please design your permission scheme to avoid giving them full root.
Proposal: ① Create the deployers group; ② Keep the code directory root:myapp, with a reviewed deployment script /usr/local/sbin/myapp-deploy that is owned by root and cannot be written by ordinary users to complete "verify package → copy → set permissions → restart"; ③ sudoers.d: %deployers ALL=(root) /usr/local/sbin/myapp-deploy (without NOPASSWD, or only for CI account NOPASSWD); ④ Escapeable commands such as cp, vi, systemctl edit are not granted; ⑤ Audit logs enter journald and are collected centrally. After using systemd in Lesson 2, you can add polkit rules to only allow myapp.service to be restarted. Take it one step further: Hand over to CI/CD (Jenkins / GitHub Actions class).
Verified teaching video
Official documentation
- passwd(5) · shadow(5) · useradd(8) · usermod(8)
- sudoers(5) · Ubuntu: sudo-rs differences and switching · sudo-rs project
Video storyboard (about 75 seconds)
This courseware cannot directly generate videos/MP3s. Storyboards and explanation scripts have been provided, which can be generated by video tools.
Screen: three cards passwd, shadow, group, Alice's row is highlighted on the three cards.
Narration: Usernames, password hashes, and group members live in three files respectively. The kernel only recognizes numeric UIDs and GIDs.
Screen: labadmin knocks sudo, a shield marked with s turns him into euid 0, then open the sudoers rulebook and find the %sudo line.
Narration: sudo is a SUID program. It first checks the rules, then verifies it with your own password, and then records the log.
Screen: less appears in the whitelist, enter !bash in less, the screen turns red and displays root#.
Narration: If the program in the whitelist can open Shell, it is equivalent to giving root. If it can be solved with groups and ACLs, don't use sudo.
Module 5 · Processes, Signals and Job Control
- Tell the key attributes of the process (PID, PPID, UID, status, priority, open files) and how to view them in
/proc/. - Interpret the process status R / S / D / T / Z / I, and know how zombie processes and orphan processes are generated and who recycles them.
- Master the default actions of common signals (HUP, INT, QUIT, KILL, TERM, STOP, TSTP, CONT, CHLD) and be able to use
kill,pkill,trapto stop the process correctly. - Use job control:
&,Ctrl+Z,jobs,fg,bg,disown,nohup, and know why production services should be left to systemd (Lesson 2).
What: What does the process have
| Attributes | Meaning | Where to see |
|---|---|---|
| PID / PPID | Process number / Parent process number; PID 1 is systemd | ps -o pid,ppid, pstree -p |
| Credentials | Real/valid/saved/filesystem UID and GID, additional groups, capabilities | Uid, Gid, Groups, Cap* of /proc/PID/status Row |
| Status | R running or ready, S interruptible sleep (waiting for events), D non-interruptible sleep (usually waiting for disk/NFS I/O), T stopped, Z zombie, I idle kernel thread | ps -o stat, suffix + Foreground process group, s session first process, l multi-threading, </N high/low priority |
| File descriptor | Opened files, pipes, sockets | ls -l /proc/PID/fd, lsof -p PID |
| Environment and command line | execve incoming argv / envp | /proc/PID/cmdline, /proc/PID/environ (separated by \0, only owner/root Readable) |
| Resources | CPU time, memory (RSS / VSZ), nice value, limit (ulimit), cgroup | top, /proc/PID/limits, /proc/PID/cgroup |
Signal (signal(7), x86-64 number)
| Signal | Number | Default action | Typical sources and uses |
|---|---|---|---|
| SIGHUP | 1 | Termination | Terminal disconnected; many daemon processes agree to "reload configuration" |
| SIGINT | 2 | Termination | Ctrl+C (sent to the foreground process group) |
| SIGQUIT | 3 | Terminate and core dump | Ctrl+\ |
| SIGKILL | 9 | Terminate (cannot be captured, cannot be ignored) | kill -9, OOM Killer; the process has no time to clean up |
| SIGTERM | 15 | Terminate (can be captured) | kill's default signal; first sent when systemd stops the service; graceful exit |
| SIGCHLD | 17 | ignore | child process status change, the parent process should wait |
| SIGCONT | 18 | continue | fg / bg |
| SIGSTOP | 19 | Stop (cannot capture) | kill -STOP |
| SIGTSTP | 20 | Stop (can capture) | Ctrl+Z |
| SIGSEGV / SIGPIPE | 11 / 13 | Terminate (SEGV and core) | Illegal memory access/write to closed pipe (yes | head in yes) |
The signal number is related to the architecture. Please write the name (kill -TERM) instead of the number in the script. For a process terminated by signal N, $? in Shell is 128+N (TERM → 143, KILL → 137, INT → 130).
Why: "TERM first and then KILL"
SIGTERM gives the program a chance to complete the request being processed, refresh the buffer, delete the lock file and temporary file, and notify the child process (gunicorn will gracefully stop the worker when receiving TERM). SIGKILL terminates the process directly by the kernel, possibly leaving behind corrupted data, stale PID/lock files, and half-written files. Correct process: kill -TERM → Wait (systemd default is 90 seconds, TimeoutStopSec) → Still do not exit and then kill -KILL. For a process in D state, even SIGKILL must wait for I/O to return before it takes effect.
How: Job Control and Session
- Each terminal is a session, and bash is the first process of the session; each pipeline is a process group (job), and only one job is in the foreground, which can read the terminal and receive Ctrl+C / Ctrl+Z.
cmd &starts the job in the background;Ctrl+Zsends SIGTSTP to stop the foreground job (T);bg %1sends SIGCONT to let it continue in the background;fg %1brings it back to the foreground and continues.- When the terminal is closed, the kernel sends SIGHUP to the session, and bash forwards the SIGHUP to its job → the background task exits.
nohup cmd &makes cmd ignore SIGHUP and write output tonohup.out;disownmakes bash not forward;setsidmakes it enter a new session. - After the parent process exits, the child process becomes orphan, adopted by PID 1 (systemd, or a process with subreaper set, such as
systemd --user) and recycled after its exit. The child process has exited but the parent process stillwait, leaving zombie (Z, which only occupies one process table entry and does not occupy memory; killing the zombie is ineffective and its parent process needs to be processed).
When: run manually vs leave it to systemd
| Method | Applicable | Disadvantages |
|---|---|---|
Foreground / & / Ctrl+Z | Interactive debugging, temporary tasks (manually run myapp in this lesson) | Stop when the terminal is closed |
nohup / tmux / screen | Long tasks (data migration) that need to span SSH disconnections | No automatic restart, log management, resource limit |
| systemd service | All production services (Lesson 2 turns myapp into myapp.service) | Need to write unit files |
kill It just sends a signal, the default is TERM, and the program can choose to process or ignore it. ② "Kill -9 is the most reliable" - it skips cleanup and is ineffective against D state and zombies; should be used as a last resort. ③ "The zombie process occupies memory, you need to kill -9 it" - the zombie is already dead, killing it is useless, you have to ask the parent process to wait or restart the parent process. ④ "Load average is CPU usage" - Linux load includes the number of tasks in R and D status, and I/O stuck will also increase the load (Lesson 7). ⑤ "Just add an & for background operation" - SIGHUP will be received when SSH is disconnected; production services are handed over to systemd. Process State Machine
The destination of sessions, process groups and signals
Process State Machine: Signal the process yourself
Start python3 -m http.server 8000 (a long-running program that can capture SIGTERM) in a simulated terminal, and then use buttons to perform job control and signal operations. The current status of the process is highlighted in the figure, and the actual command and the output of ps -o pid,ppid,stat,cmd / jobs are shown below. Illegal operations will be rejected and reasons given.
fg/bg By The bash call tcsetpgrp switches the foreground process group and sends SIGCONT; after the child process exits, the kernel turns it into a zombie and sends SIGCHLD to bash, and the bash call waitpid recycles and prints [1]+ Done or Terminated . Python's http.server throws KeyboardInterrupt for SIGINT and exits (status 130); it uses the default action for SIGTERM and terminates directly (143). Command table
| Command | Function | Key points |
|---|---|---|
ps -ef / ps aux | List all processes (System V / BSD style) | ps -eo pid,ppid,user,stat,ni,%cpu,%mem,etime,cmd --sort=-%cpu | head |
pstree -pu | Process tree (with PID and user switching) | From psmisc |
top / htop | Live view | top in P/M sort by CPU/memory, k signal, 1 expand each CPU |
pgrep -a / pkill | Find or signal by name/user/full command line | pgrep -u myapp -f gunicorn; confirm with pgrep first and then pkill |
kill -SIG PID / kill -l | Send/list signals | kill -0 PID Only check if the process exists and has permissions |
jobs -l / fg / bg / disown | Job control | %1, %+, %sleep |
nohup cmd & / setsid cmd | Ignore SIGHUP / New session | Output defaults to nohup.out |
nice -n 10 cmd / renice | Adjust CPU priority (-20 is the highest, 19 is the lowest) | Lowering the priority can be done by ordinary users, raising it requires root |
trap 'cmd' TERM INT | Capture signal in script | trap - TERM Restore default; KILL/STOP cannot be captured |
uptime / cat /proc/loadavg | Load | Comparison with nproc |
data-l="bash"
class="out" data-l="Expected output (example, excerpt)"
-bash The dash in front represents the login shell; the four values in the Uid line are real, valid, saved, and file system UID. The process title format of sshd varies with the OpenSSH version.
data-l="bash"
class="out" data-l="Expected output"
yes Writing to the closed pipe after head exit, received SIGPIPE(13) → 128+13 = 141. This is common in pipes and is usually harmless.
Objective: Practice job control, compare SIGTERM and SIGKILL, observe zombies and orphans. Environment:linuxlab, labadmin. Fees: None.
data-l="bash"
class="out" data-l="Expected output (example)"
The process running in the background has STAT without + (not in the foreground process group).
data-l="bash"
class="out" data-l="Expected output (example)"
When bash executes sleep 1 in the foreground, it will wait for it to end before running the trap, so the cleanup may be delayed by up to 1 second - this is why Systemd needs to give a timeout when stopping the service. %% represents the current job. KILL left behind a stale lock file: rm /tmp/worker.*.lock.
data-l="bash"
class="out" data-l="Expected output (example)"
kill -9 4612 will not make the zombie disappear; the parent process exits after 30 seconds, and the zombie is adopted by PID 1 and recycled immediately.
data-l="bash"
class="out" data-l="Expected output (example, after logging back in)"
PPID becomes 1 (or the user's systemd --user instance, depending on the session settings): it is orphaned and adopted. In addition, systemd-logind's KillUserProcesses=, if enabled, will kill such processes when logging out - it is not enabled by default in Ubuntu.
pkill -u "$USER" sleep; rm -f /tmp/worker.*.lock ~/linuxlab/tmp/sleep.pid(keep worker.sh). Case 1: kill -9 caused database corruption
Problem: The staff on duty felt that Redis was shutting down too slowly, so they directly kill -9. The ongoing AOF rewriting was interrupted, and it took a long time to repair the file during restart. How to: Use the service manager to stop (systemctl stop redis-server, first TERM and then press timeout KILL); increase TimeoutStopSec if necessary (Lesson 2). Principle: KILL is only used after confirming that TERM is invalid.
Case 2: SSH disconnected, migration task terminated midway
Problem: A data migration script was run in the foreground for 4 hours in SSH. After the VPN was disconnected, the script received a SIGHUP and terminated, and the data was in a semi-migrated state. How to do it: Put the long task into the tmux session, or systemd-run --unit=migrate --same-dir ./migrate.sh and run it as a temporary service (the log enters journald, Lesson 2); the script itself is made reentrant.
Case 3: Thousands of zombie processes
Problem: The self-developed Python daemon forks a child process every time it processes a task, but never waits. After a few days, tens of thousands of appear in ps, and finally touch pid_max / cgroup pids.max limit, fork failed (Resource temporarily unavailable). How to: Fix the code (use subprocess.run or handle SIGCHLD); briefly restart the parent process to clear out all zombies. Monitoring: Alarm ps -eo stat | grep -c '^Z' (the node_exporter of the Prometheus class has process status indicators).
Common Errors and Solutions
kill: (1234) - Operation not permitted
Cause: You can only signal to processes with the same real/effective UID, unless you have CAP_KILL (root).
data-l="bash"
The process still exists after kill -9
Reason: It is a zombie (Z, dead, waiting for recycling by the parent process), or in D state waiting for I/O.
data-l="bash"
Fix: Zombie → Handle its parent process; D status → Troubleshoot storage/NFS (Lesson 7).
bash: fork: retry: Resource temporarily unavailable
Cause: The number of processes limit was reached: user's ulimit -u, cgroup's pids.max (systemd's TasksMax), or system's kernel.pid_max.
data-l="bash"
The background task output confuses the terminal / the background task stopped by itself (Stopped (tty input))
Reason: The background job can still write to the terminal; it receives SIGTTIN when reading the terminal and stops.
data-l="bash"
1. Find the 5 processes with the highest memory usage (display PID, user, %MEM, command).
data-l="bash"
2. Stop all gunicorn processes of user myapp gracefully. If they still exist after 10 seconds, forcefully terminate them.
data-l="bash"
uptime shows that the load average of the 2-core machine is 12, but the CPU in top is 85% idle. What could it be? How to confirm?
Linux load statistics for tasks in R and D states. The CPU is idle but heavily loaded, indicating that a large number of tasks are in D state (waiting for disk, NFS, or other non-interruptible I/O). Confirm: ps -eo stat,pid,wchan:32,cmd | awk '$1 ~ /^D/', top's wa (iowait), vmstat 1's b column, iostat -x 1 to see the device delay; check whether the NFS mount is stuck and whether the disk is faulty. Lesson 7 dives into the USE method.
Verified teaching video
Official documentation
Video storyboard script (about 75 seconds)
This courseware cannot directly generate video/MP3. Storyboards and explanation scripts have been provided, which can be generated by video tools.
Screen: PID, PPID, UID, status, fd table are listed on the process card; the /proc/4061 directory next to it is expanded.
Narration: A process is a running program plus its identity and open files, which can be seen in the proc directory.
Screen: Press Ctrl+Z on the keyboard, the process card turns gray with T written on it; enter bg, the card turns green and moves to the "backstage" area on the right.
Narration: Ctrl+Z stops the foreground job, bg lets it continue in the background, and fg pulls it back.
Screen: Two processes receive TERM and KILL respectively. The former cleans up the lock file before exiting, and the latter disappears instantly, leaving the lock file behind.
Narration: TERM is issued first to allow the program to exit gracefully, and KILL is the last resort.
Module 6 · Package management: apt, dnf and repositories
- Explain packages, repositories, indexes, dependencies, signatures and
Signed-Byrelationship; understand Ubuntu's default deb822 file/etc/apt/sources.list.d/ubuntu.sources. - Proficient in using
apt(update / install / remove / purge / policy / hold / history) anddpkg(-l / -L / -S); know the difference between main, universe and -security, -updates. - Add the third-party repository in the correct way (keys are placed in
/etc/apt/keyrings+.sourcesfiles) and no longer use the removedapt-key. - Compare RHEL system:
dnf,rpm,/etc/yum.repos.d/*.repo,dnf history undo, version locking; understand Azure Linux's tdnf and Amazon Linux 2023 versioned warehouse.
What: two families
| Debian / Ubuntu | RHEL / Rocky / Alma / Amazon Linux / Azure Linux | |
|---|---|---|
| Package format | .deb (ar archive: control + data) | .rpm |
| Underlying tools (single package, no dependencies resolved) | dpkg, database /var/lib/dpkg | rpm, database /var/lib/rpm (EL10 is sqlite) |
| High-level tools (warehouse, dependencies, transactions) | apt (interactive) / apt-get (script, stable output) | dnf (EL10 is dnf 4.20; dnf5 for Fedora 41+); tdnf |
| Repository Configuration | /etc/apt/sources.list.d/*.sources for Azure Linux 3.0 (deb822); legacy single line *.list Deprecated (removed no earlier than 2029) | /etc/yum.repos.d/*.repo(INI) |
| Signing keys | Each repository specifies its own public key with Signed-By: (/usr/share/keyrings or /etc/apt/keyrings) | gpgcheck=1 + gpgkey=, imported into rpm database (rpm --import) |
| Installation script | preinst / postinst / prerm / postrm (can create users and start services) | %pre / %post / %preun / %postun and scriptlets |
| Configuration file protection | conffile: Ask when upgrading the /etc file you changed | %config(noreplace): The new version is saved as .rpmnew |
Ubuntu's warehouse structure
class="out" data-l="/etc/apt/sources.list.d/ubuntu.sources (26.04 example)"
| Concept | Value | Meaning |
|---|---|---|
| Suites(pocket) | resolute / -updates / -security / -backports | Version at release / stable update / security update / new version back-porting |
| Components | main (Canonical support), restricted (proprietary driver), universe (community maintenance, Ubuntu Pro provides extended security maintenance), multiverse (with license restrictions) | redis-server in universe: If your source is only enabled main, you will get "Unable to locate package" |
| URIs | Official or mirror address; the cloud is usually a regional mirror (such as Azure's azure.archive.ubuntu.com) | You will see cloud mirrors in Lessons 3 and 4 |
Why: Why signatures are important
apt downloads the warehouse's InRelease (embedded signed Release file) and verifies it with the public key specified by Signed-By; the hash of the Packages index is listed in Release, and the hash of each .deb is listed in the index. SHA256. So a public key → Release → Index → Package forms a chain of trust, which can be discovered even if the image is tampered with or uses HTTP. The old apt-key add put the third-party key into a global trust so that any repository could be signed with it - this is why it was deprecated and removed in APT 3 (26.04).
How: Steps for an apt install
apt update: Download from sourcesInRelease→ Verify signature → Download and verifyPackages,Translation, etc. are indexed to/var/lib/apt/lists/.apt install redis-server: The solver (new for APT 3) computes dependencies (redis-tools, libjemalloc, etc.) with the version to install (the highest priority candidate inapt policy).- Download
.debto/var/cache/apt/archives/and verify the hash. - Call
dpkg --unpack(run preinst, unpack files) →dpkg --configure(run postinst: e.g. createredissystem user, enable and startredis-server.service) → trigger (man-db, systemd daemon-reload). - Logged to
/var/log/apt/history.logand/var/log/dpkg.log; 26.04 can be viewed withapt history-list/apt history-info.
Debian/Ubuntu convention: Installing the service pack will automatically enable and start the service (the RHEL system does not start it by default, and requires systemctl enable --now). This is one of the most common behavioral differences between the two families.
When: Select the installation source
| Source | Advantages | Risk/cost |
|---|---|---|
| Distribution repository (apt/dnf) | Security updates arrive automatically, are compatible with system libraries, and are auditable | Older version (LTS frozen main version) |
| Manufacturer's official warehouse (Docker, Microsoft, HashiCorp...) | The latest version is still available apt Upgrade | Requires trust in additional keys; use Signed-By to limit the scope |
| Snap(Ubuntu) | Brings its own dependencies and automatically updates | Automatic update timing needs to be managed; needs to be evaluated on the server |
| Language package manager (pip / npm) in the virtual environment | Application dependencies and system isolation (myapp uses venv) | Do not use sudo pip install Pollution system Python (Ubuntu will reject with externally-managed-environment) |
curl … | sudo bash | Easy | Not auditable, non-rollback - production prohibited |
RHEL system, Azure Linux, Amazon Linux 2023 Key points
- EL10 repository: BaseOS (core OS) + AppStream (application, language runtime) + CRB (development dependency, enabled by default since AlmaLinux 10.1); EPEL provides additional community packages (
dnf install epel-release). Modularity is deprecated in RHEL 10. - dnf commonly used:
dnf install / remove / upgrade / search / info / provides / repolist / history / history undo N; version lock requirespython3-dnf-plugin-versionlock. - Azure Linux 3.0:
tdnf(Tiny DNF), the command is similar to dnf, the package collection is streamlined, mainly used for AKS nodes and container hosts. - Amazon Linux 2023: dnf; The warehouse is locked by release version (each AMI corresponds to a warehouse snapshot), use
dnf check-release-updateto check the new version, and then upgrade to the new releasever as needed (Lesson 4).
apt upgrade Will be upgraded to the next Ubuntu version" - No, that is do-release-upgrade; upgrade Only updated within the current version, full-upgrade Allows packages to be removed to resolve dependencies. ② "apt remove Deleted cleanly" - the configuration file is still there, purge was deleted only after deleting the conffile in /etc (data directories such as /var/lib/redis are usually still retained). ③ "It will take effect after installing the new kernel" - needs to be restarted (or Livepatch); /var/run/reboot-required prompts that a restart is required. ④ "apt-key can still be used" - APT 3.1 in 26.04 has been removed apt-key. ⑤ "dnf and apt will automatically start the service" - Ubuntu will, but RHEL will not. Chain of trust: from public key to package
apt install redis-server full process
Select a scenario and observe each step of apt and dpkg step by step; the failure scenario displays the actual error text and repair methods.
/var/lib/dpkg/lock-frontend and /var/lib/dpkg/lock ; Ubuntu's unattended-upgrades Security updates are installed every day by default, and the lock is often held shortly after booting. The postinst of the service package is deb-systemd-helper enabled and deb-systemd-invoke started the service (complying with policy-rc.d, starting is usually prohibited in container images). Command comparison table
| Task | Ubuntu(apt / dpkg) | RHEL system (dnf/rpm) |
|---|---|---|
| Refresh index | sudo apt update | sudo dnf makecache (usually automatic) |
| Install/specify version | sudo apt install pkg / pkg=1.2-3 | sudo dnf install pkg / pkg-1.2-3 |
| Upgrade all | sudo apt upgrade (full-upgrade allows package deletion) | sudo dnf upgrade |
| Only install security updates | unattended-upgrades (enabled by default) | sudo dnf upgrade --security |
| Delete / delete with configuration | apt remove / apt purge; apt autoremove | dnf remove (automatically clean up unnecessary dependencies) |
| Search/Details | apt search / apt show pkg | dnf search / dnf info pkg |
| Candidate versions and sources | apt policy pkg | dnf list --showduplicates pkg |
| Which package the file belongs to | dpkg -S /path | rpm -qf /path / dnf provides /path |
| What files are in the package | dpkg -L pkg | rpm -ql pkg |
| Installed list | dpkg -l / apt list --installed | rpm -qa / dnf list --installed |
| Fixed version | sudo apt-mark hold pkg | sudo dnf versionlock add pkg (plugin) |
| History/rollback | apt history-list (APT 3), /var/log/apt/history.log; rollback requires manual installation of the old version | dnf history / dnf history undo N |
| Verify installed files | dpkg --verify pkg | rpm -V pkg |
data-l="bash"
class="out" data-l="Expected output (example, excerpt)"
How to verify: Version number 5:8.0.5-1ubuntu0.1 Medium 5: Yes epoch, 8.0.5 is the upstream version, and -1ubuntu0.1 is the Ubuntu packaging revision (check the resolute version on packages.ubuntu.com). Older systems may still have /etc/apt/sources.list (comments only). URIs in cloud images point to cloud vendor images. Common mistakes: Use apt instead of apt-get in Dockerfile/scripts (apt will warn "does not have a stable CLI interface").
Standard mode for adding a third-party warehouse (take the Docker official warehouse as an example, used in the Docker class)
data-l="bash"
Key points: the key is only effective for this warehouse (Signed-By); .asc (ASCII) and .gpg (binary) is acceptable; whether the manufacturer has provided a repository for a new release (such as resolute) shall be subject to its documentation. No real additions are needed for this lesson.
Goal: Install the system dependencies (redis-server, python3-venv) required by myapp, query, fix and audit. Environment:linuxlab, labadmin. Cost: Download approximately 10–20 MB.
data-l="bash"
class="out" data-l="Expected output (example)"
Ubuntu's postinst automatically enables and starts Redis. It only listens on 127.0.0.1 (bind in /etc/redis/redis.conf).
data-l="bash"
class="out" data-l="Expected output (example)"
Pay attention to the package maintainer's approach: dedicated system user + nologin + data directory 750 - consistent with the approach of myapp in the comprehensive experiment. The specific file list, permissions and UID are subject to your system.
data-l="bash"
class="out" data-l="Expected Output (Example, 26.04)"
apt history-list is a new command for APT 3 (26.04), and the column format is an example; use /var/log/apt/history.log on 24.04. Hold is suitable for critical components that "must be tested before upgrading", but will prevent security updates from arriving and must be released in a planned manner.
data-l="bash"
data-l="bash"
RHEL 10 series AppStream provides Valkey instead of Redis (the package name and availability are subject to the actual output of dnf info); the service will not start automatically after the RHEL system is installed: sudo systemctl enable --now valkey.
Case 1: Automated deployment always fails after booting
Problem: After the new VM is started, cloud-init executes apt install immediately, and intermittently reports Could not get lock /var/lib/dpkg/lock-frontend——unattended-upgrades Security updates are being installed. How to: Use apt-get -o DPkg::Lock::Timeout=300 install … to wait for the lock; or use the packages: module in cloud-init (Lessons 3 and 4). Forbidden: Deleting the lock file or killing dpkg will cause damage to the package database.
Case 2: An apt upgrade introduced an incompatible major version
Problem: The third-party warehouse does not have a fixed version. apt upgrade upgrades the database client from 15 to 17, and the application connection fails. How to: Use apt preferences (/etc/apt/preferences.d/ Pin) or apt-mark hold to fix the major version; upgrade first in the pre-release environment; incorporate the upgrade into the change process (Lesson 3 Azure Update Manager, Lesson 4 Patch Manager).
Case 3: Hash Sum mismatch of internal mirror source
Problem: Enterprise proxy caches old Packages index but InRelease has been updated, all servers apt update report Hash Sum mismatch. How to do it: The proxy pair InRelease/Packages does not cache or set a short TTL; use an image that supports by-hash (Ubuntu repository provides Acquire-by-hash by default). Temporary solution: sudo rm -rf /var/lib/apt/lists/* && sudo apt update.
Common errors and solutions
E: Unable to locate package xxx / Package 'xxx' has no installation candidate
Cause: No apt update; wrong package name; the component (universe) is not enabled; the package is not in the current release.
data-l="bash"
Fixed: After adding universe to Components of ubuntu.sources, apt update.
W: GPG error: … NO_PUBKEY 7EA0A9C3F273FCD8 / The repository … is not signed
Cause: Signed-By points to a key file that does not exist, is not the corresponding public key, or the key has expired/rotated.
data-l="bash"
Fix: Re-download the key from the manufacturer's official HTTPS address to the path pointed by Signed-By; Do not add [trusted=yes] to bypass verification.
E: Could not get lock /var/lib/dpkg/lock-frontend. It is held by process 1234 (unattended-upgr)
data-l="bash"
Fix: Wait for it to complete. Do not rm lock files.
E: dpkg was interrupted, you must manually run 'sudo dpkg --configure -a' to correct the problem.
data-l="bash"
error: externally-managed-environment(sudo pip install)
Reason: Ubuntu's system Python is managed by apt (PEP 668), which prohibits direct writing by pip.
data-l="bash"
1. Find out which package /usr/bin/jq belongs to, and list the version and source repository of the package.
data-l="bash"
2. List the packages installed or upgraded through apt in the last 7 days (applicable to 24.04 / 26.04).
data-l="bash"
The vendor's installation document requires the execution of curl -fsSL https://vendor.example/install.sh | sudo bash. How would you evaluate and adapt?
Risk: The content of the script cannot be audited, each download may be different, run as root, cannot be rolled back, if the transmission or provider is compromised, it will be completely lost. Transformation: Download the script and review it (fixed version/hash); give priority to using the vendor's signed apt repository (/etc/apt/keyrings + .sources + Signed-By), so that both upgrades and uninstallations go through the package manager; verify in the pre-release environment; write the repository and version into configuration management (Ansible class). If you can only use a script, verify SHA256 after downloading and run it in an isolated environment.
Verified teaching video
Official documentation
- sources.list(5) (deb822 format) · 26.04 Summary for LTS users (APT 3.1) · packages.ubuntu.com: redis-server (resolute)
- DNF Command Reference · AL2023 release cadence
Video storyboard script (about 75 seconds)
This courseware cannot directly generate video/MP3. Storyboards and explanation scripts have been provided, which can be generated by video tools.
Screen: A key (Signed-By) opens the lock of InRelease, the hash on InRelease is connected to Packages, and the hash of Packages is connected to .deb.
Narration: apt's trust chain starts with a public key, and uses hashes to lock indexes and packages layer by layer.
Screen: apt install redis-server: dependency tree expansion, download progress bar, dpkg unpacking, postinst creates redis user and starts service.
Narration: apt is responsible for the warehouse and dependencies, dpkg is responsible for unpacking and running the installation script, and Ubuntu will start the service smoothly.
Screen: left and right split screen, left apt policy, right dnf list --showduplicates; bottom says hold / versionlock.
Narration: The two families have different commands but the same idea: check candidate versions, fix critical versions, and record every change.
Module 7 · Text processing: grep, sed, awk and pipes
- Use
grep(-E -i -v -c -o -n -r -w) to filter lines according to regular rules; distinguish basic regular rules (BRE) and extended regular rules (ERE). - Use
sedfor replacement, deletion, line range processing, and safe in-place editing of configuration files (-i.bak). - Use
awkto process by fields:-F,$1...$NF, conditions,BEGIN/END, associative array aggregation. - Use
sort,uniq -c,cut,tr,wc,head/tail,tee,xargscombined pipeline to answer "Top IP, 5xx distribution, P95 "Delay" issues.
What: Three main tools
| Tools | Mental model | Most commonly used |
|---|---|---|
| grep | Match regular rules line by line, select lines | grep -E ' 5[0-9]{2} ' access.log, grep -rn 'bind' /etc/redis/, grep -v '^#' f |
| sed | Stream editor: execute "address + command" line by line, rewrite lines | s/old/new/g, /^#/d, -n '10,20p', -i.bak |
| awk | Split into fields line by line, execute "mode {action}", calculation and report | awk '{print $1}', awk -F: '$3>=1000', {c[$9]++} END{for(k in c) print k,c[k]} |
Implementation differences: Ubuntu's default awk is mawk (small and fast), the RHEL system is gawk (GNU, with many extensions, such as asort, --csv); use awk -W version or awk --version to check, and when you need gawk features, sudo apt install gawk. grep and sed are GNU versions on both sides (not part of coreutils, not affected by the 26.04 rust-coreutils switch; sort, uniq, cut, tr, wc belong to coreutils).
Regular expression quick overview
| Writing | Meaning | BRE (grep / sed default) | ERE(grep -E / sed -E / awk) |
|---|---|---|---|
^ $ | Start of line / End of line | ✓ | ✓ |
. * [a-z] [^0-9] | Any character / previous item repeated 0+ times / character class / negative class | ✓ | ✓ |
+ ? {2,3} | ( ) | 1+ times / 0–1 times / times / or / grouping | Needs to be written as \+ \? \{2,3\} \| \( \) (GNU extension) | Use directly |
[[:digit:]] [[:space:]] | POSIX character class | ✓ | ✓ |
\b \d | Word boundary/number | \b is a GNU extension; \d is only available in grep -P (PCRE) | |
Why: Why learn these "old tools"
- Any Linux It is available on all platforms (including a minimized cloud image and rescue environment), and does not rely on the network or additional installation.
- Streaming processing: Several GB of logs do not need to be read into memory; both ends of the pipeline run concurrently.
- Combines naturally with output from the
journalctl,kubectl,az/awsCLI (JSON withjq, Lesson 5).
How: Pipeline data flow
class="out" data-l="Top 3 Access IP"
uniq only merges adjacent duplicate rows, so it is almost always sort | uniq -c. Sorting is affected by locale: use LC_ALL=C sort when endianness is required in scripts (also faster).
When: Which tool to choose
| Task | Preferred |
|---|---|
| Find out the line containing a certain pattern and which file a certain configuration is in | grep(-r, -l, -n) |
| Batch modify a row in the configuration, delete comments | sed (backup before modification in production or use configuration management instead) |
| Statistics by column, sum, average, group count, formatted report | awk |
| Get columns by fixed delimiter | cut -d: -f1 |
| Character replacement/deletion (uppercase and lowercase, delete carriage return) | tr |
| Convert input into command parameters | xargs (when the file name contains spaces -0 cooperate with find -print0) |
| JSON / YAML | jq / yq, do not use grep to parse JSON |
cat file | grep x is the standard way of writing" - directly grep x file, one less process. ② "sed -i is safe" - it will replace the file (new inode), the symbolic link will be replaced with a normal file, and the permissions and owners may change; first use the command without -i to preview, and then -i.bak. "awk's $0 is the 0th column" - $0 is the entire row, $NF is the last column ④ "grep -c Statistics matching times" - the statistics are the number of matched rows, the number of statistics is grep -o … | wc -l. ⑤ " . Matching point in the regular expression" - it matches any character, matches IP The points in need to be written \.. Pipeline: concurrently running process chain
awk's execution model
err[$7]++) is the core of awk's "group counting"Pipeline step-by-step simulator
Data: 12-line sample of access.log (same format as generated in environment preparation: IP - - [Time] "Method Path Protocol" Status Bytes "-" "UA" Time consuming). Select a pipeline and step through the output of each command - the results are generated by JavaScript in the page. Computed by the true semantics of the command
class="out" data-l="stdin" id="a7in" style="min-height:220px;white-space:pre-wrap;font-size:12px"
class="out" data-l="stdout" id="a7out" style="min-height:220px;white-space:pre-wrap;font-size:12px"
Command table
| Commands | Common options | Examples |
|---|---|---|
grep | -E ERE, -i Ignore case, -v inverse selection, -c count lines, -o output only matches, -n line number, -r recursive, -l list only file names, -w whole words, -A/-B/-C context | grep -rnw /etc -e 'PermitRootLogin' |
sed | -n does not print automatically, -E ERE, -i[.bak] edit in place; command s p d a i c | sed -n '/ERROR/,+2p' app.log |
awk | -F delimiter, -v var=value | awk -F: '{print $1}' /etc/passwd |
sort | -n numbers, -r reverse order, -k2,2 by column 2, -t: delimiter, -u deduplication, -h human readable size | du -sh /var/* | sort -h |
uniq | -c Count, -d only show duplicates | sort | uniq -c |
cut / tr / wc | -d -f / -d -s 'a-z' 'A-Z' / -l -w -c | tr -d '\r' < win.txt > unix.txt |
head / tail | -n, tail -f trace, tail -n +2 skip header | tail -F /var/log/syslog |
tee | -a append | cmd | tee out.txt | grep x; echo x | sudo tee /etc/f |
xargs | -0, -n, -P Parallel, -I{} | find . -name '*.log' -print0 | xargs -0 -n 50 gzip |
diff / comm | -u Unified format | diff -u redis.conf.bak redis.conf |
data-l="bash"
class="out" data-l="Expected output (example, numbers depend on generated data)"
data-l="bash"
class="out" data-l="Expected output (example)"
The log itself is sorted by time, so "per minute" statistics do not need to be sorted first. For log analysis in production, see Lesson 2 journald and Prometheus & Grafana Lesson (logs are not suitable for long-term calculation of latency quantiles).
Goal: Use pipelines to answer 5 operational questions and safely modify a copy of the configuration using sed. Environment:linuxlab, ~/linuxlab/logs/access.log (generated during environment preparation). Fees: None.
data-l="bash"
class="out" data-l="Expected output (example)"
203.0.113.7 (document reserved address) is weighted 6x in the generated data, accounting for about 1/4 of the traffic - in a real environment this is a signal to investigate.
data-l="bash"
data-l="bash"
data-l="bash"
class="out" data-l="Expected output (example)"
data-l="bash"
class="out" data-l="Expected output (example)"
The line number and default value change with the Redis version; maxmemory is commented out by default.
data-l="bash"
class="out" data-l="Expected output (example)"
We don't install it back into /etc/redis: the actual modification of the service configuration belongs to Lesson 2 (Modify → Verify → Restart → Verify → Rollback). Note that -i.bak only backs up the first time; it will not back up the second time if -i does not have a suffix.
rm ~/linuxlab/tmp/redis.conf*(keep access.log). Case 1: Locating the source of the attack within 5 minutes of the incident
Problem:Surge of website 502. How to do it:awk '$9==502 {print $1}' access.log | sort | uniq -c | sort -nr | head Found that a single network segment accounts for 80%, grep and its User-Agent is a scanner; block it on load balancing/WAF (Lesson 6 Firewall). Experience: Use pipes to get "who, when, what" first, and then decide on actions; save commonly used pipes as scripts (Lesson 5).
Case 2: sed turns the configuration file into an empty file
Problem:Operation and maintenance wrote sed 's/a/b/' app.conf > app.conf, Shell first opened (cleared) the file with O_TRUNC, and sed read an empty file. How to do it: Use sed -i.bak or write a temporary file mv; the key configuration is managed by the configuration rendering template (Ansible class).
Case 3: grep parsing JSON output leads to misjudgment
Problem: The script uses grep '"status": "ok"' to determine health. After the cloud CLI upgrade, the output format (spaces, field order) changes, and false positives are monitored. How to: Use jq -e '.status == "ok"' for structured data, or call CLI's --query/--output tsv (lessons 3 and 4).
Common errors and solutions
sed: -e expression #1, char 12: unknown option to `s'
Cause: The replacement content contains the delimiter / (such as path).
data-l="bash"
awk: line 1: syntax error at or near … / The variable is not replaced
Reason: The awk program uses double quotes, and the Shell expands $1 first; or you want to pass in the Shell variable.
data-l="bash"
grep: (standard input): binary file matches
Cause: The file contains non-text bytes such as NUL (binary and UTF-16 encoding are mixed in the log).
data-l="bash"
The sort result is "out of order": 10 is in front of 9 / different machines sort differently
Reason: Sort lexicographically instead of numerically; locale is different.
data-l="bash"
1. Count the proportion of requests for each HTTP status code in access.log (percentage, keep 1 decimal place).
data-l="bash"
2. Recursively find all file names containing 127.0.0.1 under /etc (permission errors will not be displayed).
data-l="bash"
A 30 GB log file needs to count the number of requests for each URL. sort | uniq -c took a long time and /tmp was full. How to improve?
sort needs to sort all data externally and will write a large number of files in the temporary directory. Change to awk associative array traversal once: awk '{c[$7]++} END {for (k in c) print c[k], k}' big.log | sort -nr | head, the memory is only related to the number of different URLs; if sorting is necessary, use LC_ALL=C sort -S 2G -T /data/tmp --parallel=4 to specify the memory, temporary directory and parallelism; first grep / awk filter out unnecessary lines; the long-term solution is to send the logs to the logging platform.
Verified teaching video
Official document
Video storyboard script (about 75 seconds)
This courseware cannot directly generate videos/MP3s. Storyboards and explanation scripts have been provided, which can be generated by video tools.
Screen: 2000 lines of logs flowing down like a waterfall, grep like a sieve leaving only the lines with 500.
Narration: grep is responsible for selecting rows, sed is responsible for changing rows, and awk is responsible for calculating by columns.
Screen: awk cuts a row into 13 grids, and the 7th grid (path) is thrown into counting buckets.
Narration: awk's associative array is a group counter, and you can get the number of errors for each path in one traversal.
Screen: Five processes are connected in a row with pipes and run simultaneously, and finally the list of Top 3 IPs is output.
Narration: The processes in the pipeline run at the same time, and the data is transferred like an assembly line. Sort plus uniq bar c is the most classic combination.
Module 8 · Getting Started with System Readiness Review and Troubleshooting
- Perform 12 system readiness reviews: version and support period, patches and reboots, time, disks and inodes, memory, load, failed services, listening ports, administrators and sudo, dangerous accounts, dangerous permissions, error logs.
- Master the general process of troubleshooting: Reproduction → Read the original text of the error → Positioning level (Shell/Permissions/Process/Package/Resource) → Single-variable verification → Repair → Verify → Record.
- Proficiently identify the five most common types of errors:
command not found,Permission denied,No space left on device,Address already in use,Connection refused. - Deliberately create 4 faults on the lab VM and repair them according to the troubleshooting tree.
What: 12 system readiness reviews
| # | Check items | Commands | Pass standards | Modules |
|---|---|---|---|---|
| 1 | Releases and support cycles | . /etc/os-release; echo $PRETTY_NAME | Supported LTS (26.04 / 24.04); EOL documented | M1 |
| 2 | Patches and reboots | apt list --upgradable; ls /var/run/reboot-required | No security updates to be installed; no pending restarts (or scheduled) | M6 |
| 3 | Time synchronization | timedatectl | System clock synchronized: yes; the time zone complies with the specification (the server commonly uses UTC) | No. 2 Lesson |
| 4 | Disk space and inode | df -hT -x tmpfs; df -i | Usage < 80% | M2 |
| 5 | Memory and swap | free -h | available Sufficient; no continuous paging | M5 |
| 6 | Load | uptime; nproc | 15 minute load | M5 | |
| 7 | Failed Service | systemctl --failed | 0 loaded units listed | Lesson 2 |
| 8 | Listening Ports | sudo ss -ltnup | Only the expected ports (22, native 6379, 5000); no unexpected 0.0.0.0 Listening | M5, Lesson 2 |
| 9 | Admins and sudo | getent group sudo; sudo visudo -c | Admin list is as expected; sudoers syntax is correct; no broad NOPASSWD ALL | M4 |
| 10 | Dangerous accounts | awk -F: '$3==0' /etc/passwd; sudo awk -F: '$2==""' /etc/shadow | Only root has UID 0; no empty password | M4 |
| 11 | Dangerous permissions | sudo find / -xdev -type f -perm -o+w; SUID list | No files writable by others; SUID consistent with baseline | M3 |
| 12 | Error log | journalctl -p err -b --no-pager | tail | No unexplained duplicate errors | Lesson 2 |
Why: Why should we "review" instead of "look almost the same"
- The root causes of most production accidents are mundane: full disk, incorrect certificate/time, service not set to start automatically at boot, permissions changed, and patches not applied. 12 checks cover them.
- The review results can be written into scripts (Lesson 5), written into configuration management (Ansible lesson), and access monitoring (Prometheus lesson), changing from one-time inspection to continuous assurance.
- The handover is well documented: "This machine passed the review on 2026-11-17, and the exceptions are...".
How: General process for troubleshooting
- Reproduce and copy the original text of the error: complete error message, exit code (
echo $?), and time point. Don't rely on impressions. - Location level: Is it Shell command not found (127)? Permissions (EACCES/EPERM)? Resources (ENOSPC, memory, fd, number of processes)? Network (deny/timeout/DNS)? An error in the program itself?
- Look at the evidence:
ls -l/namei -l,id,df,ss,ps, log (journalctl -u service -e). If necessary,strace -f -e trace=file,networkto see the last failed system call. - Only change one variable at a time, back up before changing (
cp -a f f.bak.$(date +%F)), and verify immediately after changing. - Fix root causes and prevent recurrence: Include readiness reviews, monitoring, or automation; write incident logs.
| Original error message | errno | First reaction |
|---|---|---|
command not found | —(Shell search failed, 127) | type -a, PATH, whether to install or not |
Permission denied | EACCES | id, namei -l, ACL, AppArmor |
Operation not permitted | EPERM | Requires capability (root), sticky, chattr +i |
No such file or directory | ENOENT | Path spelling, symbolic link target, shebang interpreter |
No space left on device | ENOSPC | df -h and df -i, du find files in large directories that have been deleted but are still open |
Address already in use | EADDRINUSE | sudo ss -ltnp 'sport = :5000' |
Connection refused | ECONNREFUSED | No one is monitoring the peer port: the service is not started or only listens to 127.0.0.1 |
Too many open files | EMFILE | ulimit -n, ls /proc/PID/fd | wc -l |
df -i), or the file has been deleted but is still open by the process (sudo lsof +L1). ③ "Connection refused is a firewall" - Firewall packet loss usually manifests astimeout; refused means that the other host clearly replies "No one is listening on this port". ④ “Do the review only once” – the machine will drift, and the review should be performed automatically and regularly. Error reporting → Level → Tool
Readiness Score Card
Select the status of a host, click "Run Review", and perform 12 checks one by one: each item displays the real command and (example) output, and gives pass/warning/fail and repair suggestions. "Linuxlab before delivery" is the state you should be in after completing this lesson.
One-click review script (read-only)
data-l="bash"
class="out" data-l="Expected Output (example, excerpt)"
This script itself is a comprehensive application of this lesson: built-in and external commands, redirection, pipes, awk filtering, sudo, and permissions. Lesson 5 will turn this into engineering (set -euo pipefail, ShellCheck, testing); the Ansible lesson will turn it into fact collection across multiple hosts.
Commonly used commands for troubleshooting
| Command | Purpose |
|---|---|
sudo ss -ltnp 'sport = :5000' | Who is listening to port 5000 |
sudo lsof -i :5000 / sudo lsof +L1 | The process corresponding to the port / Deleted but still open files |
du -xh --max-depth=1 / 2>/dev/null | sort -h | tail | Find large directory |
sudo dmesg -T | tail / journalctl -k | Kernel messages (OOM, disk errors, AppArmor) |
journalctl -u redis-server -e --no-pager | Recent logs of a service |
strace -f -e trace=%file,%network -o t.txt cmd | Find the last failed system call (grep -E '= -1' t.txt | tail) |
curl -sv http://127.0.0.1:5000/healthz | Application layer verification |
Objective: Deliberately create 4 faults and process them according to "error report → layer → evidence → repair → verification"; final run readiness review. Environment:linuxlab. Fees: None.
data-l="bash"
class="out" data-l="Expected Output (example)"
126 → The level is "execution permission"; the permission of the symbolic link itself does not matter, what is seen is the target file.
data-l="bash"
class="out" data-l="Expected Output (example)"
Space is not released after file deletion because fd 3 still has it open (number of links is 0); space is not reclaimed until fd is closed. It is common in production that deleted logs are still written by the service process - restart or let the service reopen the log (Lesson 2 logrotate).
data-l="bash"
class="out" data-l="Expected output (example, excerpt)"
Myapp will use port 5000 in the comprehensive experiment - be sure to kill %1 to release it.
data-l="bash"
class="out" data-l="Expected output (example)"
Connection refused + No monitoring → The service is not running. Lesson 2 will let myapp.service declare a dependency on redis-server (Wants=/After=).
readiness.sh in the "Command" tab, save the results to ~/linuxlab/logs/, and compare the passing standards item by item; record the reasons and plans when there are failures. sudo rmdir /mnt/small; Confirm sudo ss -ltn 'sport = :5000' No output. Case 1: Disk 100% but du cannot find large file
Problem: Root partition is full, du -sh /* only adds up to half. Root cause: The application log was deleted by rm, but the process still holds the file handle and continues to write. Method:sudo lsof +L1 Find the process and let it reopen the log (restart the service or send the signal agreed by the application); later use logrotate's copytruncate or let the application support reopening (Lesson 2).
Case 2: inode exhausted
Problem:No space left on device, but df -h only uses 40%. Root cause: Millions of small files have accumulated in the session file directory, df -i shows 100%. How to do:find /var/lib/php/sessions -type f -mmin +1440 -delete Clean, and configure periodic cleanup (systemd-tmpfiles or timer, Lesson 2); add df -i to the readiness review.
Case 3: "Time bomb" found in delivery review
Problem: Found in the new environment review: time is not synchronized (deviation of 7 minutes, which will cause TLS and cloud API signature failure), there is a legacy ALL=(ALL) NOPASSWD in , the redis monitoring of the two machines is at /etc/sudoers.d/temp: ALL0.0.0.0. How to do it: After the repair, incorporate the 12 checks into the online access control and continue to check through monitoring (Prometheus & Grafana class).
Interactive troubleshooting tree
Start from symptoms, answer questions step by step, and get diagnostic commands and repair methods. Covers common faults in all modules of this course.
1. Find the five largest directories in the root file system (not across file systems).
data-l="bash"
2. List all TCP ports and their processes listening on non-loopback addresses.
data-l="bash"
Early morning alarm: myapp returns 500, OSError: [Errno 28] No space left on device appears in the log, but df -h shows that / is only used 62%. Please write down the troubleshooting steps.
① Confirm which path failed to write (log/temporary directory), use df -h to see the file system where it is located - it may be a separately mounted /var or /tmp (tmpfs) instead of /; ② df -i Check inode; ③ sudo lsof +L1 Check deleted files that are still occupied; ④ du -xh --max-depth=1 Find the growing directory; ⑤ Release space (clean, rotate, expand), re-verify /healthz; ⑥ Prevention: disk and inode alarms (80%), log rotation, temporary file cleaning strategy, and write it down in the incident record.
Verified teaching video
Official document
Video storyboard script (about 80 seconds)
This courseware cannot directly generate video/MP3. Storyboards and explanations have been provided, which can be generated by video tools.
Screen: The scorecard composed of 12 grids lights up green one by one, with "Time Synchronization" and "Listening Port" turning red.
Narration: Before delivering a machine, use twelve inspections to confirm that it is healthy, maintainable, and has no obvious safety holes.
Screen: Five original error messages are arranged in a row, each connected to a level: command, permission, process, package, resource.
Narration: The original text of the error report usually tells you which layer the problem is at: 127 means commands, Permission denied means permissions, and Connection refused means no one is listening.
Screen: Disk 100%, still showing 100% after the file is deleted, lsof marked (deleted), reset to zero after closing the handle.
Narration: First collect evidence, then only change one variable at a time, and verify it immediately after the change.
Command cheat sheet
System identity
data-l="bash"
Shell and expansion
data-l="bash"
Files and directories
data-l="bash"
Permissions and ACL
data-l="bash"
Users, groups and sudo
data-l="bash"
Processes and signals
data-l="bash"
Software packages (Ubuntu)
data-l="bash"
Software package (RHEL system)
data-l="bash"
Text processing
data-l="bash"
Troubleshooting
data-l="bash"
Exit code and error report quick check
| Phenomena | Meaning | Check first |
|---|---|---|
$? = 127 / command not found | Command search failed | type -a, PATH, installation |
$? = 126 / Permission denied (when executing) | Found but unable to execute | x bit, noexec, directory x on path |
$? = 128+N(130 / 137 / 143) | Terminated by signal N (INT/KILL/TERM) | Who sent the signal? OOM? dmesg |
| Permission denied / Operation not permitted | EACCES / EPERM | id, namei -l, ACL, sticky, chattr |
| No space left on device | ENOSPC | df -h, df -i, lsof +L1 |
| Address already in use / Connection refused | Port occupied/no one listening | ss -ltnp, service status |
| Could not get lock /var/lib/dpkg/lock-frontend | Another apt/dpkg is running | Waiting; DPkg::Lock::Timeout |
| NO_PUBKEY / not signed | Repository signature cannot be verified | Key pointed to by Signed-By |
Comprehensive experiment + final exam
Scenario
The team wants to run myapp on linuxlab (the same sample application as the Docker / Jenkins lesson, no container is used here, running directly as a native process). Security requirements: The application runs as a dedicated non-loginable system user; the application cannot modify its own code; the configuration (including future passwords) is only changeable by root, readable by myapp, and invisible to others; dependencies are installed in a virtual environment and do not pollute the system Python; Redis only monitors the local machine.
| Path | Owner: Group | Mode | Reason |
|---|---|---|---|
/opt/myapp | root:myapp | 0750 | myapp can enter; others (including alice) cannot pass through |
/opt/myapp/app/, app.py, requirements.txt | root:myapp | 0750 / 0640 | Apps read only their own code |
/opt/myapp/venv/ | root:root | 0755 (umask 022 default) | Dependencies installed by root; outer layer 0750 blocked access by others |
/opt/myapp/run.sh | root:myapp | 0750 | Start wrapper script (Lesson 2 by ExecStart Replaced) |
/etc/myapp/, myapp.env | root:myapp | 0750 / 0640 | Configuration and Confidential |
systemctl is-active redis-server is active, sudo ss -ltn 'sport = :5000' No output (module 8's http.server Stopped),python3 -m venv --help Available. It is recommended to take a snapshot first: on the host machine multipass stop linuxlab && multipass snapshot linuxlab --name before-myapp && multipass start linuxlab. data-l="bash"
data-l="bash"
class="out" data-l="Expected output (example)"
data-l="bash"
class="out" data-l="Expected output (example, excerpt)"
labadmin's own execution of python in the venv is rejected - because /opt/myapp is 0750 root:myapp, labadmin is not in the myapp group and cannot be traversed (path resolution rules of module 3). This is exactly what we want. The dependent minor version is based on PyPI when installed.
data-l="bash"
class="out" data-l="Expected output (example)"
set -a Let the variables coming in from the source be exported automatically, so that the gunicorn process can see REDIS_HOST in the environment (Module 2: Shell variables vs environment variables). exec causes the Shell to be replaced by gunicorn (module 1), and SIGTERM is sent directly to gunicorn when stopped.
data-l="bash"
class="out" data-l="Expected output (example)"
PPID 6118 is the sudo process (sudo will fork out the command and wait for it); master 6120 forks out two workers. The log file is opened by labadmin's shell (redirection occurs before sudo).
data-l="bash"
class="out" data-l="Expected output (example)"
data-l="bash"
class="out" data-l="Expected output (example)"
data-l="bash"
class="out" data-l="Expected output (example)"
We stopped it deliberately: the manually run service will not automatically recover after the terminal is closed or restarted, and the log is only in one file - Lesson 2 will write /etc/systemd/system/myapp.service (User=myapp, EnvironmentFile=/etc/myapp/myapp.env, ExecStart=/opt/myapp/venv/bin/gunicorn …, Restart=on-failure, After=redis-server.service), and give the log to journald.
Acceptance Checklist
Open-ended self-test (6 questions)
1. Why is the venv created by root and the code owner is root instead of chown -R myapp /opt/myapp?
If the application has its own code and dependencies, any remote code execution vulnerability can write malicious code into app.py or site-packages and persist it. Owned by root, myapp is read-only, so that attackers cannot tamper with the code even if they control the process; places that need to be written (caching, uploading) should be given separate directories (such as /var/lib/myapp, Lesson 2 StateDirectory=).
2. What are the consequences of setting myapp.env to 0644? What if it is set to 0600 root:root?
0644: All local users can read the configuration, and Redis passwords and API keys added in the future will be leaked. 0600 root:root: The myapp user cannot read, ./etc/myapp/myapp.env in run.sh will fail (Permission denied), and the application fails to start. 0640 root:myapp is the balance point. In Lesson 2, systemd reads EnvironmentFile as root, so you can consider 0600 root:root.
3. Who does the log file in sudo -u myapp /opt/myapp/run.sh > ~/linuxlab/myapp.log belong to? Why?
Belongs to labadmin. The redirection is opened by labadmin's bash in the forked child process before sudo is executed (module 1); sudo only inherits this opened fd 1 to gunicorn. If you want the log to be written to a protected directory as myapp, you need to redirect it within the myapp command (such as sudo -u myapp sh -c '… > /var/log/myapp/app.log'), or give it to journald.
4. If exec is removed from run.sh, what will be the difference when stopping?
sh will fork gunicorn as a child process and wait as the parent process. pkill -f gunicorn will still hit gunicorn, but if you stop "run.sh's process" by PID and the SIGTERM is sent to sh, sh will not forward the signal (same problem with shell form CMD in the Docker lesson) and gunicorn may continue to run or become orphaned after sh is killed. systemd will kill all processes by cgroup, but the order of graceful stop will be affected.
5. Using the idea of readiness review, list what is missing before myapp goes online?
Auto-start at boot and crash restart (systemd), centralized logs and rotation (journald), resource limits (MemoryMax, TasksMax), firewall only opens 5000 for load balancing (lesson 6), TLS termination (reverse proxy), monitoring /healthz and indicators (Prometheus class), Redis Persistence and backup, dependency version locking (pip freeze generates lock files), automated deployment (Ansible/CI).
6. What needs to be changed in the same deployment on Rocky Linux 10?
Package: sudo dnf install python3 valkey (EL10 uses Valkey to replace Redis, service name valkey), and systemctl enable --now valkey (RHEL does not start automatically); python3 -m venv is usually included on EL; SELinux is enforcing, file contexts under /opt/myapp and non-standard port 5000 may require semanage adjustments (lesson 6); firewalld blocks 5000 by default (firewall-cmd --add-port=5000/tcp); the administrator group is wheel.
Final Test
Source and version description
| Topic | Verification Conclusion | Source (Accessed 2026-11-17) |
|---|---|---|
| Ubuntu LTS and support period | 26.04 LTS was released on 2026-04-23, with standard security maintenance until 2031-05, and ESM until 2036-05; 24.04 LTS standard support until 2029-05, ESM until 2034-05; 20.04 standard support ended in 2025-05; latest transition version 26.10 (2026-10) | Ubuntu release cycle; 26.04 release notes |
| Component changes in 26.04 relative to 24.04 | GA kernel 6.8 → 7.0; systemd 255 → 259 (remove cgroup v1, the last version with SysV script compatibility); APT 2.7 → 3.1 (remove apt-key, new solver, history command); Python 3.12 → 3.14; OpenSSH 9.6p1 → 10.2p1 (no DSA); chrony replaces systemd-timesyncd (new install) | Summary for LTS users |
| sudo-rs and rust-coreutils | Since 25.10, sudo is provided by sudo-rs (the original version is sudo.ws), coreutils is provided by uutils; in 26.04, cp, df, mv, rm, true are still from GNU; switch coreutils to use coreutils-from-gnu / coreutils-from-uutils package (do not use update-alternatives); sudo-rs does not support I/O logs, sudoreplay, sudo-ldap, and the prompts are different | Ubuntu Server: System utility replacements; From LTS to LTS(Ubuntu Foundations) |
| 26.04 package version | bash 5.3-2ubuntu1; python3 3.14.3; redis-server 5:8.0.5-1ubuntu0.1 (universe, source package redis) | packages.ubuntu.com(bash, python3, redis-server, resolute) |
| deb822 sources | Ubuntu uses /etc/apt/sources.list.d/ubuntu.sources; single-line format is deprecated, "no earlier than 2029" Year" removed; field Types / URIs / Suites / Components / Signed-By | sources.list(5) |
| Linux Kernel | mainline 7.4-rc3(2026-11-15); stable 7.3.4; longterm 6.18, 6.12, 6.6, 6.1, 5.15, 5.10 | kernel.org |
| systemd Upstream | Latest release v262.x (GitHub releases marked Latest); used by Ubuntu 26.04 259 | systemd releases |
| RHEL series | RHEL 10.3 and 9.9 were released on 2026-11-11 (kernel 6.12); Rocky Linux 10.2 was released in late 2026-05 (the latest official version at the time of verification); AlmaLinux 10.1 was released on 2025-11-24, 10.3 beta has been released; EL10's dnf is 4.20 (dnf5 has not entered RHEL 10) | Red Hat Developer: RHEL 10.3 / 9.9; Rocky 10.2 GA; RHEL-38831 (dnf5 moved out of EL10 build root) |
| Azure Linux | 3.0 It is the official version (tdnf); 4.0 will enter public preview in mid-2026. No GA announcement was found during verification | Reports of Microsoft Build 2026 announcement (such as Redmondmag); for Lesson 3, please check learn.microsoft.com |
| Amazon Linux 2023 | Standard support to 2027-06-30, maintenance period until 2029-06-30; quarterly version, AMI and warehouse version coupling; dnf | AL2023 release cadence |
| Multipass | latest 1.17.1; launch's --cpus (default 1), --memory (default 1G), --disk (default 5G), the image parameter can be codename/alias/version, if omitted, it will be the latest LTS; there is no option to attach additional disks in the official CLI reference | multipass launch; Multipass releases |
| Permission determination algorithm | ACL check sequence: owner → named user (∧mask) → Group (any matching entry ∧mask) → other; when mask exists, the group permission bit corresponds to mask; search permissions are required at each level of the path; CAP_DAC_OVERRIDE requires at least one x bit when executed; Linux uses fsuid for permission check | acl(5); path_resolution(7) |
| Bash expansion and exit code | Expansion order: braces, tildes, argument/variable/arithmetic/command substitution, word splitting, pathnames, dequotes; 126 / 127 / 128+N | Bash Manual; Exit Status |
| myapp | Consistent with Jenkins/GitLab class: Flask + redis + gunicorn, /healthz Return {"status":"ok"}; Depends on flask==3.1.*, redis==5.*, gunicorn==23.*; Port of this course is 5000 | Jenkins Lesson 1 |
Video Verification Instructions
This lesson only lists videos passed by YouTube oEmbed (https://www.youtube.com/oembed?url=…&format=json) on 2026-11-17 Verify the title and channel of the video:
- Linux in 100 Seconds — Fireship (Module 1)
- Introduction to Linux – Full Course for Beginners — freeCodeCamp.org (Module 1)
- Linux Directories Explained in 100 Seconds — Fireship (Module 2)
- Linux File System/Structure Explained! — DorianDotSlash (module 2)
- Linux Crash Course: Navigating the Linux Filesystem — Learn Linux TV (Module 2)
- Beginner's Guide to the Bash Terminal — Joe Collins (EzeeLinux) (Module 2)
- Linux Crash Course - Understanding File & Directory Permissions — Learn Linux TV (Module 3)
- Linux Crash Course | User Permissions - Access Control Lists (ACL) — The Technology Sandbox (Module 3)
- Linux Crash Course | File System - Permission — The Technology Sandbox (Module 3) 3)
- Linux Crash Course - Managing Users — Learn Linux TV (Module 4)
- Linux Crash Course - sudo — Learn Linux TV (Module 4)
- How to use the killer command in Linux (Linux Crash Course Series) — Learn Linux TV (Module 5)
- Using the ps Command | Efficient Process Monitoring on Linux Systems — Akamai Developers (Module 5)
- Linux Crash Course - The apt Command — Learn Linux TV (Module 6)
- Linux Crash Course - The dnf Command — Learn Linux TV (Module 6)
- Linux Crash Course - The grep Command — Learn Linux TV (Module 6) 7)
- Linux Crash Course - The sed Command — Learn Linux TV (Module 7)
- Linux Crash Course - awk — Learn Linux TV (Module 7)
- Linux Crash Course - The cut Command — Learn Linux TV (Module 7)
- 60 Linux Commands you NEED to know (in 10 minutes) — NetworkChuck (Module 8)
- 100+ Linux Things you Need to Know — Fireship (Module 8)
- The 50 Most Popular Linux & Terminal Commands - Full Course for Beginners — freeCodeCamp.org (Module 8)
oEmbed Only the title and channel were verified, and the content was not viewed segment by segment; the content description in "meta" comes from the title and public information, and may be different from the video details. Most of these videos were recorded before Ubuntu 26.04: sudo-rs prompts, rust-coreutils, deb822 sources, APT 3's new commands, etc. are subject to this lesson. There is no verified video that specifically explains the "whole process of fork/execve" and "ACL determination algorithm". The corresponding content is based on the animation and storyboard of this lesson.
Voice explanation instructions
The "Voice" page uses the built-in Web Speech API of the browser to read the Chinese explanation script (en-US) and English terminology (en-US), and does not rely on the network or external scripts. This courseware cannot embed MP3 or generate video; the explanation draft and storyboard script can be handed over to TTS or video tools to generate audio and video.
Known limitations
- The experimental commands are not executed in the real environment: There is no Ubuntu 26.04 virtual machine available when this courseware is written. All "expected outputs" are examples, in which PID, UID/GID, IP, timestamp, kernel minor version (such as
7.0.0-15), package revision number, file size, log statistics, and hash are indicative values; the output wording of rust-coreutils and the GNU version may be slightly different. - sudo-rs installation path (
/usr/lib/cargo/bin/sudo),--versionoutput, rejection wording ("I'm sorry … I'm afraid I can't do that") andsudo -lformat are not tested on 26.04; visudo is in sudo-rs Please refer tocommand -v visudofor the following provision method. - Multipass's image alias (
26.04/resolute/lts) is subject to the actual output ofmultipass find; the official document does not list the specific alias. Multipass does not have a proven "attach second disk" command, so the LVM lab in Lesson 2 uses a loopback device. - The distribution name and default systemd settings of Ubuntu 26.04 in WSL2 have not been verified. The courseware requirements are based on
wsl --list --onlineandps -p 1 -o comm=. - The default umask (0002 vs 0022) for ordinary Ubuntu users depends on the combination of
pam_umaskandUSERGROUPS_ENAB. The courseware is subject to the actual output ofumask, and the example is written according to 0002. - RHEL 10 uses Valkey to replace Redis, and AlmaLinux 10.1 starts with CRB enabled by default. Reference information such as CRB comes from second-hand reports in the release announcement. The rhellab part of Lesson 6 is optional. Please refer to the actual output of
dnf info. Unable to confirm whether Azure Linux 4.0 is GA, will be re-verified in Lesson 3. - APT 3's
apt history-listoutput column format is schematic; the version number inapt policycomes from packages.ubuntu.com (resolute), and different revisions may be seen depending on the mirror synchronization time. - The "Execute a command" animation is based on the public behavior of fork and command search in the bash source code (bash searches for commands in the parent process, handles redirection and command_not_found_handle in the child process) and the simplified implementation of system calls observable by strace, omitting vfork optimization, signal masking, and dynamic link details; the "permission determination" animation is based on acl(5) and path_resolution(7), not included Impact of LSM, mount options, and user namespace. The pipeline simulator uses JavaScript to simulate the semantics of awk/sort/uniq/sed in the browser, covering only the functions used in the example.
- myapp's Python dependency uses a version range (
flask==3.1.*, etc.), and the actual installed minor version depends on the PyPI installed; gunicorn 23 has not been tested on Python 3.14.