Courses3 levels
Level 1 · Foundations11 courses
Level 2 · Core5 courses
Level 3 · Advanced5 courses
Labs8 topics
Library Practice exams AI Range Pricing Start free

Foundations / Linux

Linux cheat sheet

Part 1 · Basics

Find your way (lesson 1)

TaskCommand
Show where you arepwd
Make a folder and its parentsmkdir -p ~/krlab/linux-basics
Go up, go backcd .., cd -
List with hidden entriesls -la
List with readable sizesls -lh
Sort by size, by time, reversedls -S, ls -t, ls -tr
Rename a filemv old new
Delete a folder and contentsrm -r cases/2026
Delete a folder only if it is emptyrmdir empty

Edit and repeat commands (lesson 2)

TaskCommand
Start or end of the lineCtrl+A, Ctrl+E
Delete a word, to the start, to the endCtrl+W, Ctrl+U, Ctrl+K
Clear the screenCtrl+L
Stop, suspend, end of inputCtrl+C, Ctrl+Z, Ctrl+D
Wake a suspended programfg
Help for a command, the manual pagels --help, man ls (/word, q)
Find a command by its job, say what a name isman -k WORD, whatis ls, type -a ls
Search the historyCtrl+R
List history, repeat the last line, repeat line 40history, !!, !40
Complete a nameTab (twice for the choices)

Variables, scripts and aliases (lesson 3)

TaskCommand
Set and read a variablename=Ada, echo "$name"
Run a script by its own namechmod +x hello.sh, ./hello.sh Ada
Make, list, remove an aliasalias lh='ls -lh', alias, unalias lh
Quote: variables work, or stay as typedecho "hi $name", echo 'hi $name'
Wildcards: any text, one characterls *.txt, ls ?.log
Keep an alias, remove it againecho "alias lh='ls -lh'" >> ~/.bashrc, sed -i '/^alias lh=/d' ~/.bashrc

Read and search text (lesson 4)

TaskCommand
Make an empty filetouch notes.txt
Show first or last lineshead -n 2 auth.log, tail -n 1 auth.log
Follow a log by name (Field note)tail -F auth.log
Count lines, words, byteswc -l, wc -w, wc -c
Read a big fileless numbers.txt
Count matching linesgrep -c "Failed password" auth.log
Match either wordgrep -cE "root|admin" auth.log
Search a fixed text (Field note)grep -F TEXT auth.log
Search folders, list namesgrep -rl "invalid user" .
Keep columnscut -d' ' -f2, cut -c1-15
Rank sources by countgrep -oE "from [0-9.]+" auth.log | cut -d' ' -f2 | sort | uniq -c | sort -rn

Fields and sums with awk (lesson 5)

TaskCommand
Print a field, the last fieldawk '{print $1}' f, awk '{print $NF}' f
Select lines by a fieldawk '$2 == 443 {print $1}' f
Skip the header lineawk 'NR > 1 && $3 > 3000' f
Add up a columnawk 'NR > 1 {s += $3} END {print s}' f
Change the separatorawk -F: '$3 == 0 {print $1}' /etc/passwd

Pipes, redirects and tee (lesson 6)

TaskCommand
Output to a file, add to a filecmd > out.txt, cmd >> out.txt
Errors to a filecmd 2> err.txt
Output and errors to one filecmd > all.txt 2>&1
Throw the errors awaycmd 2> /dev/null
Read a file as inputwc -l < file
Run the next command only on success, on failurecmd && next, cmd || next
Screen and file at oncecmd | tee out.txt
Add to a file and the screencmd | tee -a out.txt
Write several filescmd | tee a.txt b.txt
Save in the middle of a pipegrep fail jobs.txt | tee fails.txt | wc -l

Edit files (lesson 7)

TaskCommand
Open, save, leave nanonano file, Ctrl+O then Enter, Ctrl+X
Search, cut a line, paste, undo in nanoCtrl+W, Ctrl+K, Ctrl+U, Alt+U
Insert, back to Normal mode in vimi or o, Esc
Search, delete a line, undo in vim/word Enter, dd, u
Save and quit, quit without saving:wq, :q!
Two-panel file managermc (F5 copy, F6 move, F8 delete, F10 quit)

Find files and read details (lesson 8)

TaskCommand
Find by namefind . -name "*.conf"
Find by type, size, agefind . -type f -size +5k -mtime +30
Find broken symbolic linksfind . -xtype l
Find by name in the name databaselocate -i name (after sudo updatedb)
Show the facts of a filestat file, stat -c '%n %s' file
Say what kind of data a file holdsfile name
Hard link, symbolic linkln old new, ln -s target new
Show where a link pointsreadlink link

Archives with tar (lesson 9)

TaskCommand
Pack a foldertar -czf project.tar.gz project
List an archivetar -tf project.tar.gz, tar -tvf
Extract into another foldertar -xzf project.tar.gz -C restore
Extract one membertar -xzf project.tar.gz -C one project/readme.txt
Leave things outtar -czf s.tar.gz --exclude=cache project
Drop the top foldertar -xzf project.tar.gz --strip-components=1 -C flat
Use xz-J
Write and check a fingerprintsha256sum a.tar.gz > a.sha256, sha256sum -c a.sha256

Permissions (lesson 10)

TaskCommand
Show who you areid
Set owner read and write onlychmod 600 notes.txt
Set bits in symbolic formchmod u=rw,go= notes.txt
Show the default mode maskumask
Find SUID filesfind /usr/bin /usr/sbin -perm -4000 -type f 2>/dev/null
Find open directories without sticky bitfind lab -type d -perm -0002 ! -perm -1000
List what sudo allows yousudo -l

Build a log triage script (lesson 11)

TaskCommand
Count the failed loginsgrep -c "Failed password" "$1"
Rank the addresses of the failuresgrep "Failed password" "$1" | awk '{print $(NF-3)}' | sort | uniq -c | sort -rn
List accepted logins, user and addressgrep "Accepted" "$1" | awk '{print $9, $11}'
Show the report and save it./triage.sh auth.log | tee report.txt

Safety habits

Part 2 · System administration

Set up (lesson 0)

TaskCommand
Your user and groups, a fresh sudo entryid, sudo -v
Check the labbash labcheck.sh

Identify the system (lesson 1)

TaskCommand
Distribution and versioncat /etc/os-release, lsb_release -d
Read the fields as variables. /etc/os-release; echo "$VERSION_ID"
Host name, system, kernel, machine typehostnamectl
Kernel release, all kernel factsuname -r, uname -a
Kernel build textcat /proc/version
Processors, logical CPUslscpu, nproc
Raw processor and memory data/proc/cpuinfo, /proc/meminfo
Disks and partitionslsblk
All hardware, one line eachsudo lshw -short
Real machine, virtual machine or containersystemd-detect-virt
Time and time zonedate, date -u, timedatectl, journalctl --utc

Measure the load (lesson 2)

TaskCommand
Load average (1, 5, 15 minutes)uptime, compare with nproc
Memory and swapfree -h, read available
One line each secondvmstat 1 5 (r, si, so, wa)
Disk traffic, busy diskiostat -d DEVICE 1 2, iostat -dx (r_await, w_await, %util)
Live process listtop (P, M, 1, q), top -b -n 1
Network card countersip -s link show eth0
Count of socketsss -s

Check and free disk space (lesson 3)

TaskCommand
Space of the file systems, with typedf -h, df -hT /
Inodesdf -i
Size of a folderdu -sh FOLDER
Sub-folders, one leveldu -h --max-depth=1 FOLDER
Biggest firstdu -h --max-depth=1 . | sort -rh | head
Size of the content, not the blocksdu --apparent-size
Stay on one file systemdu -x
Folder with the most filesfind . -type f | cut -d/ -f2 | sort | uniq -c | sort -rn
Find a deleted file that is still openls -l /proc/PID/fd
Empty the package cache, trim the journalsudo apt-get clean, sudo journalctl --vacuum-size=200M

Partitions, file systems and mounting (lesson 4)

TaskCommand
Devices, file systems, mountslsblk -o NAME,SIZE,TYPE,FSTYPE,MOUNTPOINTS, findmnt, sudo blkid
Disk image in a filetruncate -s 64M disk.img
Write a GPT table from a scriptprintf 'label: gpt\n,16M,L\n,,L\n' | sfdisk disk.img
Read a partition tablefdisk -l disk.img
Make an ext4 file systemmkfs.ext4 -L label /dev/sdb1
Read its factsdumpe2fs -h part.img, blkid part.img
Practise a mount without a disksudo mount -t tmpfs -o size=4m tmpfs /mnt/kr, findmnt -n -o FSTYPE /mnt/kr
Attach an image as a loop device, detach itL=$(sudo losetup --find --show part.img), sudo losetup -d "$L"
Mount an image, a real partitionsudo mount -o loop part.img /mnt/kr, sudo mount /dev/sdb1 /data
Check the mount, unmountfindmnt /data, sudo umount /data
Check an fstab filefindmnt --verify, sudo mount -a
Make swap from a file, use it, stop itsudo fallocate -l 64M /swapfile, sudo chmod 600 /swapfile, sudo mkswap /swapfile, sudo swapon /swapfile, swapon --show, sudo swapoff /swapfile
LVM layers (Field note)pvcreate, vgcreate, lvcreate, lvextend, resize2fs

Watch and control processes (lesson 5)

TaskCommand
List all processes, as a treeps -ef, ps -ef --forest
Choose columns, one processps -o pid,ppid,stat,ni,cmd -p PID
Biggest memory usersps -eo pid,%mem,comm --sort=-%mem | head
Find by namepgrep -a NAME
Polite stop, forced stopkill PID, kill -9 PID
Pause, continuekill -STOP PID, kill -CONT PID
List signalskill -l
Background jobscmd &, jobs, fg %1, bg %1, nohup cmd &
Start nicer, change a running onenice -n 5 cmd, renice -n 12 -p PID
What a process really runsls -l /proc/PID/exe /proc/PID/cwd
Zombie stateZ in STAT: end its parent

Users and groups (lesson 6)

TaskCommand
Read an accountgetent passwd NAME, id NAME, groups NAME
Add a group, an accountsudo groupadd -g 2100 GROUP, sudo useradd -m -u 2001 -g GROUP -s /bin/bash NAME
Set a passwordsudo passwd NAME, passwd
Add a user to a groupsudo usermod -aG GROUP NAME
Lock, unlock, statussudo passwd -l NAME, sudo passwd -u NAME, sudo passwd -S NAME
Close a login fullysudo chage -E 0 NAME, sudo usermod -s /usr/sbin/nologin NAME
Password ageingsudo chage -M 90 -m 1 -W 7 NAME, sudo chage -l NAME, sudo chage -d 0 NAME
Remove an account, with its homesudo userdel NAME, sudo userdel -r NAME

Sudo rules and ACLs (lesson 7)

TaskCommand
Run as another usersudo -u NAME cmd, su - NAME
Check a sudo rule, install itvisudo -cf rule.sudo, sudo install -m 440 -o root -g root rule.sudo /etc/sudoers.d/NAME
A sudo rule for a group%GROUP ALL=(root) NOPASSWD: /full/path/cmd
List what a user may runsudo -l -U NAME
Show, add, remove an ACL entrygetfacl FILE, setfacl -m u:NAME:r FILE, setfacl -x u:NAME FILE, setfacl -b FILE

Services (lesson 8)

TaskCommand
List running, failed servicessystemctl list-units --type=service --state=running, systemctl --failed
State of one servicesystemctl status NAME, systemctl is-active NAME, systemctl is-enabled NAME
Start, stop, restartsudo systemctl start NAME, stop, restart
Start at boot, stop startingsudo systemctl enable NAME, sudo systemctl disable NAME, enable --now
Read a unit filesystemctl cat NAME
Read the unit files againsudo systemctl daemon-reload
Log of one servicesudo journalctl -u NAME -n 20, -o cat
Check a unit filesystemd-analyze verify FILE
Clear a failed marksudo systemctl reset-failed NAME
Replace text in a file, in placesed -i 's/OLD/NEW/' FILE

Software (lesson 9)

Taskapt and dpkgdnf and rpmpacman
Refresh the listsudo apt updatednf check-updatenot covered
See what can be upgradedapt list --upgradablednf check-updatenot covered
Upgradesudo apt upgradesudo dnf upgradesudo pacman -Syu
Install, removesudo apt install NAME, sudo apt remove NAMEdnf install, dnf removepacman -S, pacman -R
Search, detailsapt search WORD, apt show NAMEdnf search, dnf infopacman -Ss, pacman -Si
Owner of a filedpkg -S FILErpm -qf FILEpacman -Qo FILE
Files of a packagedpkg -L NAMErpm -ql NAMEpacman -Ql NAME
Verify the files of a package (Field note)sudo dpkg --verify NAMErpm -V NAMEnot covered
TaskCommand
Write and check a fingerprintsha256sum FILE > SUMS, sha256sum -c SUMS

Build from source and control the path (lesson 10)

TaskCommand
Compile one C filecc -o hello hello.c
Build, show the rule without running it, install into your foldermake, make -n install, make install PREFIX=$HOME/krlab/linux-admin/local
Show the search pathecho "$PATH" | tr ':' '\n'
Show every program of a name, the one the shell runstype -a NAME, command -v NAME
Give a variable to child programs, remove itexport NAME=value, unset NAME

Write a script (lesson 11)

TaskCommand
Stop on errors, unset variables, pipe failuresset -euo pipefail
Default for an argument${1:-default}
Chooseif [[ -r $f ]]; then ...; else ...; fi
Repeatfor x in a b c; do ...; done, while [[ $n -lt 4 ]]; do ...; done
Calculate, test a numbern=$((n + 1)), (( n ))
Tests of [[ ]]-z empty, -n not empty, -r readable, -ge -gt -lt -eq number compare, ! not
Fail on an empty variable"${dir:?dir is not set}"
Check the syntax onlybash -n script.sh
Read the exit codeecho $?

Run a script on a schedule (lesson 12)

TaskCommand
Save, install, show your crontabcrontab -l > crontab.backup, crontab FILE (replaces every job), crontab -l
Put it back, or remove itcrontab crontab.backup, crontab -r
Five cron fieldsminute hour day-of-month month day-of-week
Run once laterecho "cmd" | at now + 1 minute, atq, atrm N
Check a timer schedulesystemd-analyze calendar "Mon..Fri 06:30"
List timerssystemctl list-timers

Audit a machine (lesson 13)

TaskCommand
SUID filesfind DIR -xdev -type f -perm -4000
Directories that anybody may write to, without the sticky bitfind DIR -xdev -type d -perm -0002 ! -perm -1000
Listening TCP ports with their processesss -tlnp
Members of the admin groupgetent group sudo wheel
File systems above 80 per centdf -P | awk 'NR > 1 && $5 + 0 > 80'
Failed servicessystemctl --failed --no-legend --no-pager
Choose the report file and the logAUDIT_OUT=FILE AUDIT_LOG=LOG ./audit.sh DIR

Safety habits

Part 3 · Networking and hardening

Inspect the network (lesson 1)

TaskCommand
List addresses, one line eachip -br addr
List interfaces with countersip -s link show lo
Show the routesip route
Ask which route an address usesip route get 198.51.100.7
List listening TCP sockets with processes (sudo for other users)sudo ss -tlnp
Show one port onlyss -tln 'sport = :8000'
Serve a folder on the loopback onlypython3 -m http.server 8000 --bind 127.0.0.1 --directory site
Print only the HTTP statuscurl -s -o /dev/null -w "%{http_code}\n" URL
Resolve a name like a programgetent hosts localhost
Ask a DNS serverdig +short @127.0.0.53 localhost

Addresses, routes and names (lesson 2)

TaskCommand
Make a dummy interfacesudo ip link add krdummy0 type dummy
Bring a link up or downsudo ip link set krdummy0 up, sudo ip link set krdummy0 down
Add and remove an addresssudo ip addr add 198.51.100.10/24 dev krdummy0, sudo ip addr del 198.51.100.10/24 dev krdummy0
Add a routesudo ip route add 203.0.113.0/24 via 198.51.100.1
Add a spare default routesudo ip route add default via 198.51.100.1 dev krdummy0 metric 500
Change or remove a routesudo ip route replace ..., sudo ip route del ...
Add a local nameecho "198.51.100.20 files.lab files" | sudo tee -a /etc/hosts
Show or set a DNS server of a linkresolvectl dns, sudo resolvectl dns krdummy0 198.51.100.53
Undo the link settings of resolvedsudo resolvectl revert krdummy0
Show or set the host namehostnamectl, sudo hostnamectl set-hostname krlab-net
Check and apply netplansudo netplan generate, sudo netplan apply
Apply netplan with a rollbacksudo netplan try
Delete a virtual interfacesudo ip link del krdummy0

Where a setting is kept permanently:

SystemFileTool
Ubuntu/etc/netplan/*.yamlnetplan apply
systemd-networkd/etc/systemd/network/*.networknetworkctl reload
Desktop LinuxNetworkManager connectionsnmcli, nmtui
Older Debian/etc/network/interfacesifup, ifdown
Older RHEL and CentOS/etc/sysconfig/network-scripts/ifcfg-*ifup, ifdown

Firewall (lesson 3)

TaskCommand
List all rulessudo nft list ruleset
Make a tablesudo nft add table inet krlab
Make an input chainsudo nft add chain inet krlab input '{ type filter hook input priority 0 ; policy accept ; }'
Allow known connectionssudo nft add rule inet krlab input ct state established,related accept
Allow a port from one networksudo nft add rule inet krlab input ip saddr 198.51.100.0/28 tcp dport 8080 accept
Set the policy to drop (last)sudo nft chain inet krlab input '{ policy drop ; }'
Show rule handlessudo nft -a list chain inet krlab input
Delete one rulesudo nft delete rule inet krlab input handle 5
Delete a table (the way back)sudo nft delete table inet krlab
Check a rule file, then load itsudo nft -c -f krlab.nft, sudo nft -f krlab.nft (the file starts with table inet krlab and delete table inet krlab, so it replaces only its own table)
Keep rules at bootadd iif lo accept first in the chain, copy the file to /etc/nftables.conf, sudo systemctl enable --now nftables
ufw: set defaults, allow SSH firstsudo ufw default deny incoming, sudo ufw allow 22/tcp
ufw: allow a port from a networksudo ufw allow from 198.51.100.0/28 to any port 8080 proto tcp
ufw: switch on, list, delete, resetsudo ufw --force enable, sudo ufw status numbered, sudo ufw delete 2, sudo ufw --force reset
Test a rule from one addresscurl -s -m 2 --interface 198.51.100.10 http://198.51.100.10:8080/

SSH (lesson 4)

TaskCommand
Install and start the serversudo apt install -y openssh-server, sudo systemctl enable --now ssh
Connectssh kr_ops@localhost, ssh -i lab_key kr_ops@localhost (-p PORT for another port)
Make a key pairssh-keygen -t ed25519 -f ./lab_key -C "you@krbox"
Install a public keyssh-copy-id -i lab_key.pub kr_ops@localhost
Show the settings that sshd usessudo sshd -T | grep -E '^(permitrootlogin|passwordauthentication|kbdinteractiveauthentication)'
Check the configurationsudo sshd -t
Read a file without restartsudo systemctl reload ssh
Listen on the loopback on Ubuntu 24.04ListenAddress 127.0.0.1 in a drop-in, then sudo systemctl disable --now ssh.socket, sudo systemctl restart ssh
Prove that the first value winsput PermitRootLogin yes in 00-test.conf, read sudo sshd -T | grep permitrootlogin, remove the file
Remove a stale host keyssh-keygen -R localhost
Show the host key fingerprintssh-keygen -lf /etc/ssh/ssh_host_ed25519_key.pub
Stop SSHsudo systemctl disable --now ssh
Clean up the labsudo sed -i '/you@krbox/d' /root/.ssh/authorized_keys, sudo userdel -r kr_guest, sudo passwd -l kr_ops

The options that matter in /etc/ssh/sshd_config.d/*.conf: ListenAddress ADDRESS, PermitRootLogin no, PasswordAuthentication no, KbdInteractiveAuthentication no, PubkeyAuthentication yes, AllowUsers NAME, Port N. The first value that sshd reads wins.

Copy files (lesson 5)

TaskCommand
Move the server to port 2222add Port 2222 to 01-krlab.conf, sudo sshd -t, sudo systemctl restart ssh
Upload a filescp -P 2222 -i "$KEY" report.txt kr_ops@localhost:/tmp/report.txt
Download a filescp -P 2222 -i "$KEY" kr_ops@localhost:/tmp/report.txt back.txt
Copy a folderscp -r -P 2222 -i "$KEY" project kr_ops@localhost:/tmp/project
Keep times and modesscp -p ...
Prove a copy is identicalsha256sum FILE, cmp FILE1 FILE2
Copy only what changedrsync -av -e "ssh -p 2222 -i $KEY" project/ kr_ops@localhost:/tmp/rs/

GnuPG (lesson 6)

TaskCommand
Use a lab keyringmkdir -m 700 alice; export GNUPGHOME=$PWD/alice
Make a key pairgpg --batch --passphrase '' --quick-generate-key "Alice Lab <alice@krbox.lab>" default default 1y
List public and private keysgpg --list-keys, gpg --list-secret-keys
Export a public keygpg --armor --export alice@krbox.lab > alice.pub.asc
Import a keygpg --import bob.pub.asc
Read a fingerprintgpg --fingerprint bob@krbox.lab
Certify a key for yourselfgpg --quick-lsign-key FINGERPRINT
Encrypt for a persongpg --armor --encrypt --recipient bob@krbox.lab plan.txt
Decryptgpg --output plan.txt --decrypt plan.txt.asc
Sign a textgpg --clearsign notice.txt
Make a detached signaturegpg --armor --detach-sign tool.tar.gz
Verifygpg --verify notice.txt.asc, gpg --verify tool.tar.gz.asc tool.tar.gz
Stop the agents, forget the lab keyringGNUPGHOME=$PWD/alice gpgconf --kill gpg-agent, unset GNUPGHOME

chroot (lesson 7)

TaskCommand
List the libraries of a programldd /bin/ls
Copy a program with its pathcp --parents /bin/ls jail/
Run a program in a jailsudo chroot jail /bin/ls /
Start a shell in a jailsudo chroot jail /bin/bash
Read the root of a processsudo readlink /proc/PID/root
List the namespaces of a processls -l /proc/self/ns
Run a program in a new host name spacesudo unshare --uts sh -c 'hostname krjail; hostname'
Run a program in a new process spacesudo unshare --pid --fork --mount-proc ps -e

Web stack (lesson 8)

TaskCommand
Install on Ubuntusudo apt install -y apache2 mariadb-server php libapache2-mod-php php-mysql
Check each partsystemctl is-active apache2 mariadb, apache2 -v, php -v, curl -sI http://127.0.0.1/
Run SQL as the administratorsudo mariadb -e "SHOW DATABASES"
Give the least rightsGRANT SELECT ON krshop.products TO 'kr_web'@'localhost';
Find anonymous accountssudo mariadb -e "SELECT user,host FROM mysql.user"
Remove themsudo mariadb -e "DROP USER IF EXISTS ''@'localhost'; DROP DATABASE IF EXISTS test;"
Keep the database on the loopbackbind-address = 127.0.0.1 in /etc/mysql/mariadb.conf.d/99-krlab.cnf
Hide the version, stop listingServerTokens Prod, ServerSignature Off, Options -Indexes
Enable a configuration and check itsudo a2enconf zz-krlab, sudo apache2ctl configtest, sudo systemctl reload apache2
Lock the web foldersudo chown -R root:www-data /var/www/html, find ... -type d -exec chmod 750 {} +, find ... -type f -exec chmod 640 {} +
Find entries that others can writesudo find /var/www/html -perm -o+w

Packages on other families (not tested here): CentOS and RHEL httpd mariadb-server php php-mysqlnd, Arch apache mariadb php php-apache.

The kernel (lesson 9)

TaskCommand
Show the releaseuname -r
Read a parametersysctl net.ipv4.ip_forward, cat /proc/sys/net/ipv4/ip_forward
Change it nowsudo sysctl -w net.ipv4.icmp_echo_ignore_all=1
Keep ita line NAME = VALUE in /etc/sysctl.d/90-krlab.conf, sudo sysctl -p FILE or sudo sysctl --system
List the loaded moduleslsmod
Read a module (licence)modinfo -F license dummy
See what a load would dosudo modprobe -n -v vxlan
Load or remove a modulesudo modprobe NAME, sudo modprobe -r NAME
Get the build tools and the sourcesudo apt install -y build-essential bc flex bison libssl-dev libelf-dev libncurses-dev linux-source
Write a default configurationmake defconfig
Start from the config of the running kernelcp /boot/config-$(uname -r) .config, scripts/config --set-str LOCALVERSION "-krlab", scripts/config --set-str SYSTEM_TRUSTED_KEYS "" --set-str SYSTEM_REVOCATION_KEYS "", scripts/config --disable DEBUG_INFO_BTF --disable DEBUG_INFO_DWARF5 --enable DEBUG_INFO_NONE
Change an optionscripts/config --disable ISO9660_FS, scripts/config --state ISO9660_FS
Fill in the restmake olddefconfig
Build, install, boot loadermake -j"$(nproc)", sudo make modules_install, sudo make install, sudo update-grub

A hardening check (lesson 10)

TaskCommand
Build a sample tree, good or weakbash sample.sh lab good, bash sample.sh lab weak
Check a tree, or the real systembash krharden-check.sh lab, sudo bash krharden-check.sh
Use the result in a scriptexit code 0 when every check is ok, 1 when one is FAIL
First or last value winssshd: the first value. sysctl, MariaDB: the last value

Safety habits

Part 4 · Operations and troubleshooting

Follow the boot process (lesson 1)

TaskCommand
Tell UEFI from BIOS[ -d /sys/firmware/efi ] && echo UEFI
Show the kernel command line, the kernelcat /proc/cmdline, uname -r
List the files of the initial RAM disksudo lsinitramfs /boot/initrd.img
Show and set the default targetsystemctl get-default, sudo systemctl set-default multi-user.target
Time of the boot, slowest units, critical chainsystemd-analyze, systemd-analyze blame, systemd-analyze critical-chain
List boots, read the last boot, errors onlyjournalctl --list-boots, journalctl -b -1, journalctl -b -p err
Kernel messagesjournalctl -k, sudo dmesg
Rebuild the boot menu after a changesudo update-grub (never edit grub.cfg by hand)
Read the reason of a panicgrep -B2 "Kernel panic" panic.log
Boot to a shell (GRUB, key e)systemd.unit=rescue.target (needs a root password), or init=/bin/bash on Ubuntu

Containers (lessons 2 and 3)

TaskCommand
Pull an imagepodman pull docker.io/library/alpine:3.20
Run once and deletepodman run --rm IMAGE COMMAND
Run in the background with a portpodman run -d --name NAME -p 8088:80 IMAGE
List containers, all of thempodman ps, podman ps -a
Logs, a command inside, stop, removepodman logs NAME, podman exec NAME CMD, podman stop NAME, podman rm NAME
Make and use a volumepodman volume create V, podman run -v V:/data IMAGE
Bind a folder read-only-v "$PWD/site:/usr/share/nginx/html:ro"
Make a networkpodman network create NET, podman run --network NET IMAGE
Build and list an imagepodman build -t NAME:1 FOLDER, podman images
Read the digest of an imagepodman image inspect IMAGE --format '{{.Digest}}'
Make a pod with a published portpodman pod create --name P -p 8090:80, podman run --pod P ...
Pod to YAML, YAML to pod, removepodman kube generate P -f p.yaml, podman kube play p.yaml, podman kube down p.yaml

Track changes with Git (lesson 4)

TaskCommand
Start a repository, set who you aregit init -b main R, git config user.name "You"
Status, stage, commitgit status --short, git add FILE, git commit -m "text"
Show changesgit diff, git diff --staged, git log --oneline --graph
Branch, switch, mergegit switch -c NAME, git switch main, git merge NAME
Finish a merge after a conflictedit the file, git add FILE, git commit --no-edit
Throw away or undo a changegit restore FILE, git revert --no-edit COMMIT
Tag a releasegit tag -a v1.0 -m "text"
Make and use a remotegit init --bare -b main r.git, git remote add origin PATH, git push -u origin main --tags
Copy a repositorygit clone SOURCE FOLDER
Find a commit by textgit log --oneline -S TEXT
Remove a path from all historygit filter-repo --invert-paths --path .env --force
Ignore a fileecho ".env" >> .gitignore

Describe systems as code (lesson 5)

TaskCommand
Check a JSON filepython3 -m json.tool FILE
Read YAML as datapython3 -c 'import yaml; print(yaml.safe_load(open("f.yaml")))'
Validate a description without applying it (refuses an unknown key, a missing key, a bad mode, an empty or unsafe path, a section that is not a list)python3 converge.py desired.yaml --check
Apply it, and apply it againpython3 converge.py desired.yaml (the second run: changed: 0)
Install a pre-commit hookcp pre-commit.sh .git/hooks/pre-commit; chmod +x .git/hooks/pre-commit
Skip a hook once (the server still checks)git commit --no-verify

Troubleshoot the network (lesson 6)

TaskCommand
Run a command in a private namespacesudo ip netns exec NS COMMAND
Address, route, route for one addressip -br addr, ip route, ip route get ADDRESS
Reach a neighbourping -c 1 -W 2 ADDRESS
Resolve a name the way programs dogetent hosts NAME
Request and read the exit codecurl -sS -m 3 URL (6 no such name, 7 refused or no route, 28 time-out: read whether the message says Resolving or Connection)
Listening ports on the server (sudo shows other users' processes)sudo ss -tlnp
Firewall rulessudo nft list ruleset

Troubleshoot CPU and memory (lesson 7)

TaskCommand
Busiest processesps -eo pid,pcpu,ni,stat,args --sort=-pcpu | head
One process nowtop -b -n 2 -d 3 -p PID
Limit the CPU of a servicesudo systemd-run --unit U -p CPUQuota=20% CMD, systemctl set-property --runtime U CPUQuota=5%
Find zombies and their parentps -eo pid,ppid,stat,args | awk '$3 ~ /^Z/'
Limit memory, wait, read the resultsudo systemd-run --wait -p MemoryMax=50M -p MemorySwapMax=0 CMD (oom-kill)
Memory and its pressurefree -m, cat /proc/pressure/memory
Swapswapon --show, free -m, sysctl vm.swappiness
Memory and swap of a unitsystemctl status U | grep Memory:

Troubleshoot storage (lesson 8)

TaskCommand
Space, inodesdf -h PATH, df -i PATH
Biggest filessudo du -ah PATH | sort -rh | head
Inodes by foldersudo du --inodes -d 1 PATH
Deleted files that are still opensudo lsof -nP +aL1 PATH 2>/dev/null
Empty an open file: > /proc/PID/fd/N
Mount optionsfindmnt -no OPTIONS PATH
Remount read-writesudo mount -o remount,rw PATH
Check an unmounted file system, change nothingsudo fsck -f -n DEVICE
Mount an image file through a loop devicesudo mount -o loop FILE PATH

Troubleshoot logins, permissions and services (lesson 9)

TaskCommand
Account line, password status, expirygetent passwd NAME, passwd -S NAME, chage -l NAME
Change the shell, unlocksudo usermod -s /bin/bash NAME, sudo passwd -u NAME
Modes of every part of a pathnamei -l PATH
Run one command as another usersudo -u NAME COMMAND
What sudo allows a user, check a rule filesudo -l -U NAME, sudo visudo -cf FILE
Why a unit failssystemctl status U, journalctl -u U, systemd-analyze verify FILE
Status codes200/CHDIR folder, 203/EXEC program, 217/USER account

Build a troubleshooting kit (lesson 10)

TaskCommand
Collect the evidence bundlebash kr-evidence.sh -o bundles
Give the bundle a fixed nameKR_STAMP=demo bash kr-evidence.sh
Check the sealcd bundles/evidence-demo && sha256sum -c manifest.sha256
Pack it for the tickettar -czf case.tar.gz -C bundles evidence-demo

Safety habits