← Revision notes Linux Fundamentals 0 / 24 done

student@linux:~$ man linux-fundamentals

Linux Fundamentals.

Revision notes for all 24 lessons of Linux Fundamentals, 3rd Edition by Sander van Vugt, built from the video transcripts. Commands sit in copyable terminal blocks, with tips and warnings called out. Search any command, tick lessons off as you finish them, and your progress stays in this browser. The command examples were reconstructed from the narration, so check flags with man when in doubt.

24lessons
4modules
61terminal blocks
24labs
0%your progress
Module 1 Basics & Shell Lessons 1–9 Β· 9 lessons 0 of 9 done Module 2 Users, Permissions, Storage Lessons 10–12 Β· 3 lessons 0 of 3 done Module 3 Networking & Administration Lessons 13–20 Β· 8 lessons 0 of 8 done Module 4 Containers, Kernel, Security Lessons 21–24 Β· 4 lessons 0 of 4 done

Lesson 1Installing Linux

Goal: understand what Linux is and why it succeeded, how distributions relate, and install Red Hat family, Ubuntu, WSL or a cloud instance.

1.1 Understanding the Linux operating system

  • Linux descends from Unix (dominant in the 70s–90s). It grew out of the Free Software Foundation / GNU movement: free tools plus open-source licences that guarantee access to source code.
  • By the 1980s GNU had most tools; the missing piece was a kernel. 1991: Linus Torvalds announced an open-source kernel on Usenet. 1992: first kernel release. Kernel + GNU tools = a usable OS.
  • Distributions bundle kernel + tools to make installation easy. Early ones (Yggdrasil, Slackware) no longer matter; Red Hat and Ubuntu are among the most popular now.
  • Torvalds also created Git, the de facto standard for open-source collaboration; most Linux software has a Git project anyone can download and contribute to.

1.2 The success of Linux

  • Open source makes the platform a commodity: vendors don't spend effort on the platform itself.
  • More secure in practice: anyone can inspect the code and propose a fix, so you don't wait months for a patch. Also free, and available for any CPU architecture.
  • Used for web, database and AI servers, public cloud, containers, embedded devices, Android, automotive, media players.
  • The one area it isn't dominant: the end-user desktop, mainly because Microsoft Office has no Linux version.

1.3 Linux distributions

  • Open source means many choices (editors, GUIs, package managers). A distribution makes those choices for you and may add features and support.
  • Hundreds exist, but at least ~90% of the software is the same: GNU core utilities, the kernel (lightly patched), common tools for permissions/processes/files, and systemd to manage services.
  • Differences are mainly in the installer, package management and network configuration.
FamilyMembers and role
Red Hat (since 1994, commercial support)RHEL (flagship, needs a licence). CentOS Stream is the development platform feeding RHEL. Fedora is the community distro with the latest software (good for a learning laptop); software stabilises Fedora β†’ CentOS Stream β†’ RHEL. Rebuilds of RHEL source: Oracle Linux, Rocky Linux, AlmaLinux, all "Red Hat family", effectively the same.
Debian (since 1994, educational roots)Ubuntu (Canonical): focus on a usable desktop; desktop and server editions. Claimed ~60% of developers use Ubuntu; ~60% of business users use RHEL family.
Ubuntu releases: LTS every two years, at least 5 years support (+2 more with a paid option). Interim releases every 6 months have short support. For anything long-lived choose LTS.

1.4 Installing Red Hat family (CentOS Stream demo)

  • Download from centos.org (CentOS Stream) or developers.redhat.com (RHEL). Pick the version (10 in the demo) and the right platform (ARM64 for Apple Silicon).
  • Requirements: 2 GB RAM (1 GB can work with no GUI), 10 GB disk, and a second disk needed later in the course. Instructor uses VMware Fusion (free on macOS); VMware Workstation on Windows. A VM is the most flexible way.
  • Use the installation pattern Server with GUI. The demo VM got 4 GB RAM and a 20 GB disk.
  • Installer: choose language/region, then create a user (student) with administrative privileges ticked, leave root without a password, accept automatic partitioning after reviewing the target disk, then Begin Installation and reboot.
  • The login screen is the GNOME desktop.

1.5 Installing Ubuntu

  • Download from ubuntu.com β†’ Ubuntu Desktop (LTS by default). Minimum 1 GB RAM, 10 GB disk, plus a second disk later. On Apple Silicon the default LTS ISO is Intel only, so an ARM64 image from cdimage.ubuntu.com is needed.
  • Boot gives a live system (try without installing). Choose Install Ubuntu, interactive installation, default software selection.
  • Tick third-party drivers (graphics/Wi-Fi) and additional media codecs. Choose "Erase disk and install Ubuntu" (safe in a VM, dangerous on a real PC). Create user student, require a password to log in, skip Active Directory, pick the time zone, Install (~15 min), restart.
  • Ubuntu also uses GNOME, with a slightly different look.

1.6 Windows Subsystem for Linux (WSL)

  • Runs an Ubuntu instance (or other distros) on top of Windows, using parts of Windows for the boot process and kernel (a Microsoft WSL kernel), so it is not a full Linux command-line experience. The instructor recommends a VM or cloud instance instead for learning.
  • Steps: enable Hyper-V in Windows features, restart, open PowerShell as administrator, install, restart, then install a distribution.
wsl --install
wsl --install Ubuntu     # create the student user + password
uname -r                 # shows the Microsoft WSL kernel
ls

1.7 Linux in the cloud (AWS example)

  • AWS Console β†’ EC2 β†’ Launch instance. A default VPC exists in a new account.
  • Choose a name, an OS image (AMI; pick free tier eligible). Amazon Linux is similar to RHEL but cheaper (no licence cost). Instance type t2.micro (or t2.nano: 1 vCPU, 0.5 GB) is fine for a test drive.
  • Create or select an SSH key pair (public/private key authentication; keep the .pem file locally and use ssh -i later). Set the network/subnet from your VPC and a security group allowing SSH (port 22).
  • Launch, then Connect β†’ connect using a public IP for a browser terminal (logs in as ec2-user). Try free -m and df -h.
Cost: beyond free-tier usage you are billed. Terminate the instance when done.

Lab: installing CentOS Stream 10 with advanced options

  • The lab and its solution video are the same walkthrough: a second install showing options the first skipped.
  • Root account is disabled by default; you can enable it and set a password, but always keep a regular administrator user for daily work.
  • Software selection patterns: Server with GUI (recommended for this course) or Minimal install for the lowest hardware needs, plus extra package groups (e.g. virtualization tools).
  • Networking: set a hostname (e.g. centos.example.com). Default is DHCP; for static IPs choose Configure β†’ IPv4 and enter address, netmask (e.g. 192.168.29.11/24), gateway and DNS. Only do this if you know the correct network values.
Back to top ↑

Lesson 2Using Essential Tools

Goal: log in, use sudo, learn command-line conventions, seven starter commands, and get help with man and friends.

2.1 Logging in

  • You need a user account; installers create an administrator user by default. The root user is unrestricted and often has no password (Ubuntu doesn't even offer one) – don't log in as root.
  • Login can be from a console (text), a GUI, or remotely via SSH. GNOME is the de facto GUI (Red Hat, Ubuntu…), but servers often have none, so focus on the command line.
  • The console login lands in the bash shell. In the GUI the same thing is the Terminal (search "term").

2.2 Using sudo

  • sudo runs one command with escalated privileges: sudo ls /root. Only members of the admin group can use it: wheel on Red Hat family, sudo on Ubuntu. (sudo can also be limited to specific tasks.)
whoami                # current user
id                    # uid, gid and group memberships (look for wheel / sudo)
ls -l /root           # permission denied as a normal user
sudo ls -l /root      # asks for YOUR password, then works

2.3 Command-line essentials

  • Linux is case sensitive (LS β‰  ls). There is always an exception to any generic rule (e.g. quitting an interface may be Ctrl‑C, q or quit), because of decentralised development.
  • Long options start with -- (uname --help); short options start with - and can be combined: ls -l -r -t = ls -lrt.
  • command --help prints a usage summary. Some options exist only in short form (-l), others in both (-k / --kibibytes).

2.4 Seven essential tools

CommandWhat it does
whoamiShow your username
pwdPrint working directory (the prompt shows ~ for your home)
ls / ls -aList files; -a includes hidden files (names starting with a dot, a convention only)
touch fileCreate an empty file, handy to test whether you can write in a directory
cat fileDisplay a text file (e.g. cat ~/.bashrc, a startup file)
passwdChange your password (admins can change others'). Errors such as "authentication token manipulation error" mean it failed, e.g. new = old
ip aShow IP configuration: lo = loopback 127.0.0.1; the real interface (e.g. ens160, name varies) holds the address for remote access; IPv6 shown too
The prompt ends with $ for an ordinary user and # for root.

2.5 Getting help with man

  • Why man: it matches the system you're on (accurate), works on disconnected systems, doesn't "hallucinate" like gen‑AI, and is what you get in Linux+, RHCSA, LFCS exams (no Internet).
  • Sections to know: 1 user commands, 5 configuration files, 8 administrator commands (need root).
  • Reading the synopsis: [ ] optional; {a|b} choose one; ... repeatable; UPPERCASE/bold = placeholder to replace (e.g. FILE). Examples are near the end; SEE ALSO lists related pages.
  • Keys: /text search, n next match, space page down, q quit. The header shows the command in uppercase for historical (typewriter) reasons.
  • info is a clunky alternative (menus with *, Enter to follow, u up, q quit). You can work with Linux without it.

2.6 Finding the right man page

  • Pages are indexed in the mandb. man -k keyword (same as apropos keyword) searches names and descriptions.
  • If nothing is found on a fresh system, generate the database: sudo mandb (normally a daily scheduled job).
  • Filter big result lists with grep, e.g. only admin commands: man -k user | grep 8 β†’ finds useradd, then man useradd.
  • "nothing appropriate" = no match; try other keywords.
man -k user | grep 8
sudo mandb

2.7 Other help systems

  • Priority: command --help (quick, used constantly because nobody memorises all options) β†’ man (more detail) β†’ rarely info and /usr/share/doc.

2.8 Command review

whoami, ls, ip a, cat, passwd, touch (test writability), pwd, man, apropos (= man -k), mandb (admin), info.

Lab: change the hostname and bring a link down

  1. man -k hostname searches descriptions too β†’ hostnamectl (section 1/8). Set it with hostnamectl hostname linfen.example.org. Open a new terminal (exit and reopen) to see the new name; config changes often need a restart of the thing reading them, not the whole system.
  2. ip help β†’ ip link help (help flag errors, but still prints help). Find the device with ip link show.
  3. sudo ip link set ens160 down; without sudo you get "operation not permitted". Bring it back with sudo ip link set ens160 up.
Shortcut: Ctrl+A jumps to the start of the command line (to add sudo in front of the previous command).
Bringing the link down kills your networking; bring it up again.
Back to top ↑

Lesson 3Using GNOME

Goal: log in to the GNOME desktop, start applications, use the terminal and tweak useful settings.

3.1 Logging in

  • GNOME is the most common Linux display manager / desktop (used on Red Hat and Ubuntu); KDE is another. Skills transfer: it's all about finding the right graphical element.
  • Login is handled by GDM (GNOME Display Manager; the name covers both the whole package and the login process). It lists existing users; use Other for an unlisted user. After login you get the GNOME shell.
  • Ubuntu shows a sidebar of common apps; CentOS has a menu at the top-left and a dock at the bottom. Same engine underneath.

3.2 Starting applications

  • Use the Activities menu / search bar: type part of a name (e.g. term for Terminal, power for power settings). Show Apps lists everything installed.
  • Example setting: screen blanks after 5 minutes by default; set Screen blank β†’ Never (also the screensaver on CentOS).
  • Virtual desktops: apps can sit on separate desktops; Activities shows them so you can switch.
  • Firefox wasn't installed on the CentOS install in the demo; the Files utility works as another example app.

3.3 Using a terminal

  • The Terminal is the most important GNOME app. Start it by typing term and Enter.
  • Ctrl+Shift++ enlarges the font. Preferences β†’ Profiles controls behaviour and appearance.
echo hello world

3.4 Useful settings

  • Network menu β†’ Wired Settings β†’ gear icon for IPv4: DHCP or manual configuration.
  • Sound: output volume and a Test button for speakers.
  • Settings is the central place for every system setting.

Lab: GNOME customisation

  1. Log out via power menu β†’ Log Out, then log back in through GDM.
  2. Disable screen saver / blanking in Settings (Power).
  3. Terminal β†’ Preferences: choose a profile palette for black text on a white background (or edit the profile colours); try other palettes to see the effect live.
  4. Behavior β†’ Bell: disable the audible bell (beep on mistakes) and the visual bell.
Back to top ↑

Lesson 4Essential File Management

Goal: know the file system hierarchy, list files, use wildcards, and copy, move, create and remove files and directories.

4.1 The Linux file system hierarchy

  • Everything is a file: configuration (mostly ASCII text), devices (device files), programs. Files live in directories; a storage device is mounted on a directory (e.g. a USB drive).
  • Layout is standardised by the File System Hierarchy Standard (FHS) from the Linux Foundation, so it looks much the same on all distributions.
  • A regular user can write only in their home directory and /tmp. Test write access with touch.
  • cd / then tree shows the layout; some entries are symlinks (shown with ls -l); colours depend on terminal settings, ignore them.
DirectoryPurpose
/bootEverything needed to boot, incl. the kernel (vmlinuz-6.12…)
/devDevice files to talk to hardware (e.g. disk nvme0n1)
/etcConfiguration files, e.g. /etc/os-release (distribution info)
/homeUsers' own environments
/procLive view into the kernel, e.g. /proc/cpuinfo
/usrProgram files. /usr/bin normal binaries, /usr/sbin binaries needing root. Package-installed software goes in /usr/bin|sbin; self-made in /usr/local/bin|sbin
/varDynamically created data, e.g. /var/log; on CentOS /var/log/messages is the main system log (besides the systemd journal)

4.2 Listing files with ls

  • -a hidden files, -l long listing, -d show the directory itself not its contents, -t sort by time (newest first), -r reverse. ls -lrt puts the most recently modified file last.
  • Columns of ls -l: type character (d directory, - file, l link) Β· permissions (rwx) Β· hard link count Β· user owner Β· group owner Β· size Β· date Β· name.
ls -ld /etc     # properties of the directory itself
ls -lrt /etc    # what changed last? (at the bottom)

4.3 Wildcards (globbing)

PatternMatches
*any characters, any length: ls a*
?exactly one character: ls a?
[nm]one of the listed characters, e.g. ls a[nm]*; ranges [a-c]*
{1..100}brace expansion (shell): touch file{1..100}, mkdir data{a,b,c}
Use ls -d a* so matching directories are listed by name, not expanded. "Permission denied" lines appear because you aren't root.

4.4 Copying with cp

  • cp src dest. Pitfall: if dest doesn't exist, cp creates a file with that name. Add a trailing slash (cp /etc/hosts mydir/) to force "directory" – you then get "Not a directory" if it doesn't exist.
  • -R recursive (copy directories), -a archive (keeps attributes, includes hidden files). For complete directory copies, tar (covered later) is better.
  • . = current directory: cp /etc/hosts .

4.5 Working with directories

  • cd with no argument goes home. mkdir dir creates; mkdir -p a/b/c creates the whole path (without -p it fails if the parent is missing).
  • rmdir only removes empty directories; rm -rf works with content.
  • As a normal user mkdir /data is denied; use sudo.

4.6 Absolute and relative paths

  • Absolute: from root, always unambiguous (/var/log/messages). Relative: from the current directory (log/messages when in /var; ./log/messages same thing). .. = one directory up (from /var/empty: ../log/messages).
  • Advice: use absolute paths to avoid confusion.

4.7 Moving with mv

  • mv moves and renames (renaming = moving to a new name). ~ = home.
  • A moved file keeps its properties and permissions; a copied file gets permissions according to its new destination.

4.8 Removing with rm

  • rm -i asks for each file; rm -f force without asking; rm -rf dir removes a whole tree silently.
  • rm -rf --no-preserve-root / would try to delete everything: as a normal user it fails with "permission denied", but it's dangerous (even your home could be hit). Never run it with sudo.
  • Brace expansion has limits: touch file{1..1000000} fails with "argument list too long"; 1000 files is fine.

4.9 Command review

ls, cp, mkdir, rmdir, mv, rm (plus tree, cd, pwd).

Lab: build a directory structure and sort files

  1. Create the tree in one go: cd /tmp; mkdir -p files/pictures files/photos files/videos; check with tree files.
  2. Copy files starting with a, b, c from /etc: cp /etc/[a-c]* files/ (errors for directories/unreadable files are fine; no -R, no sudo).
  3. cd files; mv [ab]* photos/; mv c* videos/ then verify with tree.
Back to top ↑

Lesson 5Advanced File Management Tools

Goal: links, find / xargs / locate / which, archiving and compression with tar, and mounts.

5.1 Hard and symbolic links (concept)

  • File names live in the directory table; a link is a pointer to another file. Every file has exactly one inode (the complete administration of the file: properties and data blocks) and the inode does not contain the name.
  • Hard link: another name pointing to the same inode on the same file system. Names are fully independent: remove either one first, nothing breaks. Not possible on directories.
  • Symbolic link (shortcut): a name pointing to another name. Can point to directories and across devices, but if the target name is removed the link becomes invalid (dangling).

5.2 Managing links

  • Example: /bin β†’ /usr/bin, /lib β†’ /usr/lib, /sbin β†’ /usr/sbin are symlinks. Old FHS put boot-critical files in /bin; that requirement was dropped, but scripts referencing /bin/passwd must still work, so symlinks keep compatibility.
  • Use case for hard links: one script needed by several directories; a hard link keeps all in sync, copies diverge.
mkdir course1 course2
nano course1/setup.sh
ln course1/setup.sh course2/setup.sh     # hard link: same inode
ls -il course*/setup.sh                  # -i shows inode numbers (equal)
# edit either one β†’ both change

ln -s setup.sh install.sh                # symbolic link (target first, then link name)
rm setup.sh                              # install.sh now broken ("No such file or directory")
ln course2/setup.sh course1/setup.sh     # recreate from the surviving hard link; fixed

5.3 find

  • Searches by name, user, size, permissions, type… Most thorough, but slow on huge file systems. Use sudo to avoid "permission denied" noise.
  • -name is an exact match; use wildcards: -name '*hosts*'.
  • -exec CMD {} \; runs CMD on every result; {} = the found file, \; closes the exec. Forgetting {} runs the command on the current directory.
  • -type f files only (avoids trying to copy directories).
sudo find / -name hosts
sudo find / -user linda
sudo find / -size +200M
sudo find / -perm -4000                  # files with SUID bit (explained in the permissions lesson)
sudo find /home -user linda -type f -exec ls -l {} \;
sudo mkdir /root/linda; sudo find / -user linda -type f -exec cp -a {} /root/linda \;

5.4 Advanced find options

  • Several -exec blocks can be chained, each closed with \; (missing one gives "missing argument to -exec").
  • 2>/dev/null suppresses error messages. ; separates two commands on one line (create the target dir first).
  • -printf formats output; | xargs grep … searches inside found files (put sudo before xargs too).
sudo find / -type f -size +100M
find /etc -exec grep -l student {} \; -exec cp {} /find-contents \; 2>/dev/null
sudo find /etc -type f | sudo xargs grep 127.0.0.1
sudo find /etc -name '*.ini' -printf '%s,%b\n' | sort

5.5 xargs

  • Builds commands from standard input (normally a pipe); lets commands that can't read piped input work. Faster and more general than find -exec.
  • -n 1 feeds arguments one at a time to commands that accept one. Don't use xargs with ls; use find.
touch {1..10}.log; ls *.log | xargs rm -f
find / -type f -size +100M | xargs rm -f
echo linda lisa laurie | sudo xargs -n 1 useradd
tail -n 3 /etc/passwd

5.6 which and locate

  • locate is much faster than find but uses a database built by sudo updatedb; refresh it periodically (cron or systemd timer). It matches a text pattern, no wildcards needed.
  • which shows where an executable is, searching the PATH. With command substitution $(…): ls -l $(which passwd).

5.7 Archiving with tar

  • tar = tape archiver. c create, x extract, t list, v verbose, f file name. Extraction goes to the current directory; use -C path to change it.
  • Compression flags: z gzip, j bzip2, J xz. Listing/extracting detects compression automatically.
  • Options work with or without a dash (BSD style tar cvf vs System V style tar -cvf); tar and ps honour BSD origins.
  • Reading /etc fully needs sudo. file identifies a file by its magic number, not its extension (e.g. "POSIX tar archive").
sudo tar cvf etc.tar /etc
sudo tar czvf etc.tar.gz /etc        # gzip (~25% of original size)
sudo tar cjvf etc.tar.bz2 /etc       # bzip2
sudo tar cJvf etc.tar.xz /etc        # xz (smallest, slowest)
tar tvf etc.tar.xz                   # list
tar xvf etc.tar.xz -C /tmp           # extract elsewhere
file etc

5.8 Compression comparison

Tool (tar flag)Notes
gzip (-z)Most common, very fast, reasonable ratio
bzip2 (-j)Better ratio, a little slower (about twice gzip's time in the demo)
xz (-J)Best ratio, much slower (4Γ— bzip2 time), so less commonly used

Measure with time (shell built-in; use /usr/bin/time for more detail): real = wall clock, user = user-space CPU, sys = kernel time.

5.9 Mounting file systems

  • The hierarchy starts at /, which sits on a partition or logical volume. Making a device accessible on a directory is a mount. /boot is usually its own mount; a USB stick mounts dynamically (e.g. /run/media/student/…).
CommandShows
lsblkBlock devices and mount points (clear overview; disk nvme0n1, optical sr0, USB sda)
mountAll mounts incl. many internal ones; filter: mount | grep '^/' (only real devices)
df -hMounted devices with free space
findmntTree of mounts (noisy)

5.10 Command review

ln, find, locate/updatedb, which (searches PATH), tar, gzip/bzip2/xz, file, mount, df, findmnt, lsblk.

Lab: find, link, archive

  1. Files under 1000 bytes in /etc β†’ /tmp/files/pictures. man find β†’ -size: +n, -n (less than), suffix c = bytes. mkdir -p /tmp/files/pictures; sudo find /etc -type f -size -1000c -exec cp {} /tmp/files/pictures \;
  2. Symlink to /var in /tmp/files: cd /tmp/files; ln -s /var . (target first, then where).
  3. Compressed archive of /home: sudo tar -czvf home.tgz /home (.tgz = tar+gzip; needs sudo to read other homes).
  4. Extract with relative names into /tmp/archive: mkdir ../archive; sudo tar -xvf home.tgz -C ../archive; check with tree.
  5. Clean up with relative names (rm -rf archive etc files in /tmp), using sudo per command. Avoid opening a root shell: one careless command can damage the system.
Back to top ↑

Lesson 6Working with Text Files

Goal: edit text with nano and vim, view files (more, less, head, tail, cat, tac) and search with grep.

6.1 Text editors

  • Work is mostly on the command line, so you need a terminal editor. nano is easy and the default on many distributions; vim (vi improved) is powerful, programmable and always available (some systems only have vi), so learn it anyway.
  • nano: just type; the bottom bar lists keys. ^ = Ctrl, M- = Meta (usually Alt). Ctrl+X exit (asks "save modified buffer?" – the changes are in memory until you confirm and give a file name).
  • Set the default editor: export EDITOR=$(which vim). Make it persistent for all users by appending to /etc/bashrc. Pitfall: a single > overwrites the file (and you have no write permission as a normal user); use >> and run the whole command with sudo sh -c '…' so the redirect also runs privileged.
nano mynewfile
export EDITOR=$(which vim)
sudo sh -c 'echo export EDITOR=$(which vim) >> /etc/bashrc'

6.2 Understanding vim

  • vim starts in command mode; press i or o to get into insert mode; Esc returns to command mode. Don't memorise everything: master a handful of commands.
  • Run vimtutor (about 20 minutes) for an on-system tutorial.
Key / commandMeaning
:wq!write, quit, don't complain. ZZ (shift‑ZZ) = write and quit
:q!quit without saving ("desperate mode")
u / Ctrl+Rundo / redo
dd, 3dddelete current line / 3 lines
:%s/old/new/gglobal substitute (without g, only the first match per line)
v, d, yvisual mode select, delete, yank (copy)
/textsearch
gg / Gtop / bottom of file
w / bnext / previous word
^ / $start / end of line
dwdelete a word
O / oopen a line above / below
:set numbershow line numbers
rreplace one character
Visual mode + G + d can wipe the whole file; recover with u or :q!.

6.3 Creating text files with vim

  • Demo of :%s/linux/Linux/g, w/b, ^/$, dw then u, O to add a line, :set number.
  • Swap files: if you close the terminal window without quitting, vim leaves .file.swp. On reopening, vim offers (R)ecover, open read‑only, or delete it. Recovery restored even the last line typed.

6.4 more and less

  • Pagers read a file page by page. less is the default and the engine behind man (same keys: /search, q). more originally only moved forward (hence the name); "more or less" they're the same now.
  • Logs: sudo less /var/log/messages (Ubuntu: /var/log/syslog).

6.5 head and tail

  • tail = last 10 lines by default, tail -3; head = first lines. Combine for one line: head -3 /etc/passwd | tail -1 (Unix philosophy: small tools joined by pipes).
  • tail -f /var/log/messages follows new lines live (stop with Ctrl+C, q doesn't work).

6.6 cat and tac

  • cat -A shows non‑printing characters ($ = end of line), -n numbers all lines, -b numbers non‑empty lines, -s squeezes repeated blank lines. tac prints the file in reverse order.

6.7 grep

  • Searches text or regular expressions in files or piped output (more in lesson 7).
OptionEffect
-iignore case
-vinvert: lines that do not match
-llist only file names
-rrecursive (needed for directories)
-A5 / -B5 / -C55 lines after / before / around the match
ps aux | grep ssh | grep -v grep      # hide the grep process itself
sudo grep -r linda /etc               # file name: matching line
sudo grep -rl linda /etc              # file names only
ps fax | grep -B5 grep                # parents of a process in the tree
sudo grep -iA5 root /etc/ssh/sshd_config

6.8 Review

nano, vimtutor/vim, more/less, head, tail, cat, tac, grep.

Lab: users file, grep, tail, tac

  1. vim users β†’ i, type lines such as Anna, Annabelle, Anna Bell, banana, Esc, ZZ. (Reused in lesson 7 for regular expressions.)
  2. grep Anna users
  3. Last line only: tail -1 users
  4. Reverse order: tac users
Back to top ↑

Lesson 7Advanced Text File Processing

Goal: extract columns (cut, sort), match patterns (regular expressions), and transform text (tr, awk, sed).

7.1 cut and sort

  • Many Linux text files are column based (e.g. /etc/passwd: field 1 = user name, field 3 = user ID). cut needs a delimiter (-d) and a field (-f).
  • sort is alphabetical by default (1, 10, 2…); sort -n sorts numerically.
cut -f3 /etc/passwd             # useless: no delimiter given
cut -d: -f3 /etc/passwd         # user IDs
cut -d: -f3 /etc/passwd | sort -n

7.2 Regular expressions

  • Text patterns used by grep, vim, awk, sed (not for file names). Always put them in single quotes so the shell doesn't interpret special characters. Don't confuse them with globbing wildcards: * means something completely different. Example: grep 'a*' *.txt, where the first part is the regex, the second the glob.
  • Basic regexes work with most tools; extended ones need grep -E (egrep). Perl has its own flavour that grep won't understand, so be careful with examples found online. Reference: man 7 regex.
PatternMeaning / example
^ $anchors: start / end of line ('^an', 'ana$')
.any single character; '^.$' = lines with exactly one character
\< \> / \bword boundaries: '\banna\b' = "anna" as a whole word
*zero or more of the preceding char: '^a.*x$'
.*[[:space:]].*line containing a space or tab (POSIX classes)
+ (ERE)one or more: grep -E 'bo+t'
? (ERE)zero or one: 'bo?t' matches bt and bot
{n,m}repetition; basic regex needs \{3\}, extended uses {3} (grep -E). E.g. three n's in a row: 'n\{3\}'
a|b (ERE)either: grep -E 'svm|vmx'

Common beginner error: using -E with a basic-regex pattern (or vice versa) gives "no match".

Advanced examples (just to read):

sudo grep -E '[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}' /var/log/messages   # IP addresses
sudo grep -E '([A-Fa-f0-9]{2}:){5}[A-Fa-f0-9]{2}' /var/log/messages                # MAC addresses
sudo grep -E '\b[0-9]{4}-[0-9]{2}-[0-9]{2}\b' /var/log/messages                      # dates
sudo grep -oE 'https?://[A-Za-z0-9./?=_-]+' /var/log/messages                      # URLs (-o prints only the match)
logger 192.168.29.11    # writes a test line into the log

7.3 tr (translate)

  • Translates one set of characters to another; handy to normalise case before scripting. Prefer [:lower:] β†’ [:upper:] over a-z (which breaks with accented letters).
echo hello | tr '[:lower:]' '[:upper:]'     # HELLO
echo hello | tr 'a-m' 'n-z'                  # simple letter shift

7.4 awk

  • A 1970s text-processing/scripting language; today useful to filter and print fields. The program is in single quotes. $0 = whole line, $1, $2… fields; -F sets the delimiter. Default separator: whitespace.
  • awk is not good at sorting; use sort -t: -k3 -n.
awk '{ print $0 }' /etc/passwd
awk -F: '{ print $4 }' /etc/passwd
awk -F: '/linda/ { print $4 }' /etc/passwd          # only matching lines
awk -F: '$3 > 999 { print $1 }' /etc/passwd         # regular users (UID > 999)
sort -t: -k3 -n /etc/passwd                         # numeric sort on field 3

7.5 sed (stream editor)

  • Non-interactive editor, another Unix relic; edits text programmatically. -n + p prints a line; -i edits the file in place; s/old/new/g substitutes; Nd deletes line N without opening the file (handy when a tool complains about "error on line N").
  • Combine with a shell for loop; often a wildcard does the same job: sed -i s/hello/bye/ *.conf.
sed -n 5p /etc/passwd              # print line 5
sed -i 's/anna/ANNA/g' regex       # in-place substitute
sed -i -e 2d regex                 # delete line 2
echo hello > 1.conf; echo hello > 2.conf
for i in *.conf; do sed -i s/hello/bye/ $i; done

7.6 Review

grep (filter), awk (filter and print fields), sed (stream editor), tr (translate), cut, sort.

Lab solution summary

  1. Delete the 5th line of users: sed -i 5d users
  2. First column of ps aux: ps aux | awk '{ print $1 }'
  3. Files in /etc with lines starting with "root": sudo grep -ril '^root' /etc (-l names only, -r recursive, -i ignore case)
  4. Lines with three n's: grep 'n.*n.*n' users (the strict three-in-a-row form is 'nnn'; nothing says the n's must be adjacent)
  5. Lines ending in "ana": grep 'ana$' users
Back to top ↑

Lesson 8Connecting to a Server

Goal: understand root, use su and sudo safely, configure sudoers, and connect to remote servers with SSH, scp and rsync.

8.1 Understanding the root user

  • Linux has two worlds: kernel space (the kernel, drivers, hardware access) and user space (applications and users). The boundary is guarded by permissions and system calls.
  • root exists on every distribution and lives in kernel space, so permissions don't apply to it: it can read any file even without permission. That makes it very dangerous. Never log in as root; modern distros often give root no password. Use sudo (better) or su (poorer choice).

8.2 su

  • su lisa opens a subshell as lisa (needs lisa's password unless you are root). su alone = root shell (root's password).
  • A plain su keeps much of your environment. Use su - (su - lisa) for a login shell with the target user's environment.
  • root can become anyone without a password. Typical use: test whether a user's permissions work. From an admin account: sudo su - linda (asks for your password).

8.3 sudo

  • Grants specific or all tasks with elevated rights. The default admin user is in group wheel (Red Hat, if you created a root password there is no default admin) or sudo (Ubuntu, root has no password).
  • After entering your password, a token is cached for 5 minutes, so further sudo commands don't ask again.
  • sudo -i opens a root shell (prompt ends in #); use only when you know many privileged commands follow, and exit afterwards.
  • Redirects and pipes are handled by your current shell, so sudo echo hello >> /var/log/messages fails. Run the whole command in a privileged shell: sudo sh -c "echo hello >> /var/log/messages".

8.4 A simple sudo configuration

  • Config: /etc/sudoers, edit with sudo visudo (syntax-checks; uses your $EDITOR). Alternatively add drop-in files to /etc/sudoers.d/ (#includedir).
  • Default line: %wheel ALL=(ALL) ALL (group wheel may run everything from everywhere, with password). NOPASSWD: ALL works but is insecure, avoid it.
  • Lengthen the password cache:
Defaults timestamp_type=global
Defaults timestamp_timeout=240        # minutes (4 hours)
On CentOS 10 the terminal title bar changes colour when running with elevated privileges. The new timeout only applies once the old token has expired.

8.5 SSH, scp and rsync

  • Remote access needs the SSH server running (port 22). Install and enable:
# Ubuntu
sudo apt install openssh-server
# Red Hat family
sudo dnf install openssh-server
sudo systemctl enable --now sshd
systemctl status sshd        # (Ubuntu: ssh); old way: service sshd status
ip a                          # find the server's IP address
  • Client: native ssh on Linux/macOS; on Windows use e.g. MobaXterm. By default it tries your local user name; use ssh user@host otherwise. First connection asks you to accept the host key fingerprint, stored for later identity checks.
  • Run a command remotely: ssh lisa@host whoami. Same shell-metacharacter rule as sudo: ssh user@host whoami >> file redirects locally; ssh user@host 'sh -c "whoami >> file"' redirects on the remote.
  • scp: simple secure copy, e.g. scp /etc/hosts 192.168.29.138:/tmp. rsync over SSH synchronises (skips unchanged parts), best for directories.
ssh student@192.168.29.138
scp /etc/hosts student@192.168.29.138:/tmp
rsync -av --progress documents student@192.168.29.138:/home/student

8.6 Working with Linux from Windows

  • Open the WSL Ubuntu from the search bar (Ubuntu). Better: MobaXterm β†’ Session β†’ SSH β†’ host, username (and port) β†’ accept the key β†’ log in; sessions (incl. WSL) are saved.
  • Recommendation: MobaXterm for remote access, a VM for the most direct experience, WSL as a last resort.

8.7 Review

su, sudo, visudo, ssh, scp, rsync.

Lab: sudo password timeout of 4 hours

  1. sudo visudo, then add Defaults timestamp_type=global and Defaults timestamp_timeout=240; save.
  2. It takes effect only after the current token (5 min) expires; the next password entry is then valid for 4 hours.
Back to top ↑

Lesson 9Working with the Bash Shell

Goal: understand where the shell sits, then use redirection, pipes, history, completion, variables, aliases, shortcuts and startup files.

9.1 The shell and other core components

  • Layers: hardware ← kernel (talks to hardware via drivers = kernel modules) ← C library (libc) providing system calls ← shell (the user's command interface).

9.2 I/O redirection and piping

Stream / operatorUse
stdin (0) <wc -l < /etc/passwd; rarely needed because file arguments already work as input
stdout (1) >writes to a file, overwrites an existing one (dangerous)
>>append instead of overwrite
stderr (2) 2>redirect errors: grep -r root /proc 2>/dev/null
&>both stdout and stderr (nothing on screen, useful in scripts)
| pipeoutput of one command is input of the next (ps aux | grep http)
teesends output to a file and on into the pipe: ps aux | tee psfile | grep ssh
  • Check success of the last command with echo $? (exit code; 0 = ok, non-zero = problem; grep returns 1/2 when nothing found/error).
  • Unix philosophy: many small specialised commands combined with pipes.

9.3 History

  • Commands are kept in memory and written to ~/.bash_history when the session closes.
CommandEffect
historylist; -c clear, -w write now, -d N delete line N (e.g. a mistyped clear-text password)
Ctrl+Rreverse search anywhere in a command; press again for older matches
!416repeat history line 416

9.4 Command-line completion

  • Tab completes commands, variables and file names; with several options press Tab twice to list them.
  • The bash-completion package (often preinstalled) also completes sub-commands/options (ip addr show), so you rarely need help for complex commands.

9.5 Variables

  • A variable is a label with a dynamic value; read with $. Scripts use them instead of hard-coded values. System variables: $PATH (where binaries are searched), $SHELL, $USER, $HISTSIZE. env lists the environment.
  • Set: COLOR=red. By default only the current shell knows it; export COLOR=red makes it available in subshells (test with bash, then echo $COLOR, exit).

9.6 Other bash features

  • alias: alias list='ls -l'; plain alias lists them. Not persistent unless put in a startup file.
  • Shortcuts: Ctrl+L clear screen, Ctrl+U wipe the line, Ctrl+A / Ctrl+E start / end of line, Ctrl+C interrupt, Ctrl+D exit / end of input.

9.7 Bash startup files

FileWhen / purpose
/etc/environmentlist of variables, first processed (empty on Red Hat)
/etc/profilesystem-wide, at login; a complex script, treat as read-only
/etc/profile.d/*.shdrop-in directory: put custom .sh files here (.csh files are ignored by bash)
/etc/bashrcsystem-wide, read every time a (sub)shell starts
~/.bash_profile, ~/.bashrcper-user versions of the above
~/.bash_logoutruns at logout (cleanup)
# /etc/profile.d/custom.sh   (system-wide, don't edit /etc/profile)
alias list='ls -l'
export COLOR=green

Open a new terminal to pick it up. Files in profile.d run in alphabetical order, so a later one wins for the same variable.

9.8 Review

tee, history, alias, export.

Lab: alias and variable for all users

sudo vim /etc/profile.d/sander.sh      # name just needs to end in .sh
alias ipconfig="ip addr show"          # quotes needed when the command has spaces
export COLOR=red                       # export so subshells see it
  • Aliases are automatically available in subshells; variables need export.
  • Reopen the terminal: ipconfig works and echo $COLOR shows red (it beats green from custom.sh because sander.sh sorts after custom.sh).
Back to top ↑

Lesson 10User and Group Management

Goal: understand users and ownership, create and modify users/groups, set defaults and password ageing, and manage sessions.

10.1 Understanding users

  • A user is an entity that is granted permissions. Mostly used by services (so they don't run as root with too many rights), plus IT staff. End users normally log in to applications, not Linux itself. See owners with ps aux.
  • Users live in /etc/passwd; system users are at the top (e.g. lp, sssd, rtkit), with shell /sbin/nologin so they can never log in. Docs: man 5 passwd.
lp:x:4:7:lp:/var/spool/lpd:/sbin/nologin
name : password placeholder : UID : primary GID : comment (GCOS) : home : shell

10.2 Ownership

  • Access is based on ownership: whoever creates a file is the user owner, and the creator's primary group becomes the group owner.
  • Every user belongs to at least one group. Most distros use private groups: creating user linda also creates group linda with only her in it.
  • sudo su - linda, id (uid, gid, groups), touch lindafile; ls -l shows linda:linda.

10.3 Creating users with useradd

  • sudo useradd anna. On Ubuntu use useradd -m to get a home directory (Red Hat creates one by default). adduser also exists; pick one command and stick to it.
  • Defaults come from /etc/login.defs (change it before creating users; existing users aren't updated) and useradd -D. Many entries say "not supported" because PAM now handles them.
  • Important there: PASS_MAX_DAYS (default 99999 days β‰ˆ 272 years, set to e.g. 99), UID_MIN/MAX, GID_MIN/MAX.
  • Set a password: sudo passwd anna; hashes live in /etc/shadow (sudo tail -5 /etc/shadow).

10.4 Creating groups with groupadd

  • sudo groupadd sales. Add a user as secondary group member: sudo usermod -aG sales anna.
  • Careful: usermod -G wheel anna (no -a) replaces all secondary groups. Always use -aG to append.

10.5 User and group properties

  • /etc/passwd fields: name, UID, GID (primary group only), GCOS/comment (old General Electric Comprehensive Operating System field; now a free description), home directory, shell.
  • grep anna /etc/passwd or getent passwd anna. getent also queries external sources such as LDAP, which is why it's useful in central-authentication environments.
  • Passwords are in /etc/shadow. Change generic properties with usermod, passwords with passwd.
  • Groups are in /etc/group; secondary memberships are recorded there (passwd has room for only one group). Use id to see a user's groups.

10.6 Defaults for new users

  • useradd -D, /etc/login.defs, and the skeleton directory /etc/skel: its content is copied into every new home directory (test: sudo touch /etc/skel/myfile, create user bob, sudo su - bob; ls -a).
  • There's no easy way to apply new defaults to existing users; loop over users with usermod/passwd.

10.7 Password properties

  • Users change their own password with passwd. Admins use passwd and chage (change ageing). chage -l user lists; plain sudo chage linda prompts for each setting (recommended over passwd -x/-n/-w).
chage settingMeaning
Minimumdays before the password can be changed again (e.g. 3)
Maximumdays until it must change (e.g. 30)
Warningdays of warning before expiry (e.g. 1)
Inactive / Expiredays after expiry until the account locks / absolute account expiry date
  • Values are in /etc/shadow as hash, days since 1 Jan 1970 of last change, min, max, warning, inactive, expiry.
  • Non-interactive password: Red Hat echo password | sudo passwd --stdin bob. Ubuntu doesn't have --stdin; use echo bob:password | sudo chpasswd, which exists on both, so prefer it. Weak passwords only produce a warning when you use sudo.
  • In shadow a ! in the second field means no password set yet.

10.8 Managing current sessions

  • who (compact) and w (also shows what each user is doing). sudo chvt 6 switches to virtual terminal 6 (back with sudo chvt 2).
  • loginctl (systemd): list-sessions, list-users, show-session ID, show-user NAME, terminate-session ID (kill an unexpected session immediately). Not available without systemd.

10.9 Review

useradd, usermod, userdel, groupadd/groupmod/groupdel, id, getent, passwd, chage, w, who, loginctl.

Lab: four users and three groups

sudo groupadd sales; sudo groupadd account; sudo groupadd users    # some may already exist
sudo useradd -G sales,users laura                 # new users: -G is safe
sudo useradd -G account,users anouk
sudo usermod -aG sales,users linda                # existing: -aG
sudo usermod -aG account,users anna
for i in anna anouk linda laura; do
  echo password | sudo passwd --stdin $i
  sudo passwd -x 60 $i                            # expire after 60 days
done
sudo passwd -S linda                              # check the 60
# Ubuntu: useradd -m for a home directory

Remember the loop structure: for i in list; do …; done with $i as the current item, and sudo before passwd (not before echo).

Back to top ↑

Lesson 11Permissions Management

Goal: control access with basic permissions (rwx), special permissions (SUID, SGID, sticky bit) and umask.

11.1 Basic permissions

PermissionOctalOn a fileOn a directory
r read4read contentlist contents (ls)
w write2modify contentadd / remove files
x execute1run it (if executable)enter it (cd)
On directories you effectively always need r + x together; without x you can do nothing there.

Three sets exist: basic permissions (the important ones), advanced permissions, and ACLs.

11.2 Managing basic permissions

  • Permissions are given to user, group, others (ugo). A file has one user owner and one group owner. Creator = user owner; creator's primary group = group owner.
  • Order of work: first ownership, then the permission mode.
  • chown anna file (user), chown anna:sales /data/sales (user and group), chgrp sales /data/sales (group only).
  • chmod absolute mode: chmod 750 file = user 7 (4+2+1 rwx), group 5 (r-x), others 0. Relative mode: chmod +x script, chmod u+w file, chmod g+w dir. Best practice: absolute for full control, relative for quick changes.
sudo mkdir -p /data/sales          # -p because /data doesn't exist
sudo chgrp sales /data/sales
sudo chmod 770 /data/sales
Deleting a file needs write permission on the directory, not on the file. User anna can delete a root-owned file in her own home directory because she has w on /home/anna.

11.3 Advanced permissions

PermissionOctalEffect
SUID set user ID4Files only: runs as the file's owner. Dangerous; avoid except where needed
SGID set group ID2Files: run as group owner (rare). Directories: new items inherit the directory's group owner
Sticky bit1Directories: a user may only delete files they own (or if they own the directory)

11.4 Managing advanced permissions

  • Shared group directory: files created by linda in /data/sales would be group-owned by linda. Set SGID: sudo chmod g+s /data/sales; new files become group sales. Check with ls -ld: shows rws in the group part.
  • Problem: any group member with w on the directory can delete others' files (laura removed linda's). Fix with the sticky bit: sudo chmod +t /data/sales; then "operation not permitted".
  • Tip: set SGID and sticky bit in relative mode (easier).
  • Notation: special bits share the x position. Lowercase s/t = special bit plus execute; uppercase S/T = special bit without execute (e.g. drwxrws---T style output when others have no x).
  • SUID example: /usr/bin/passwd is -rwsr-xr-x. While it runs you are root, which is needed to write /etc/shadow (not even root has permissions on it, but root ignores permissions). Find all SUID files: sudo find / -perm -4000 2>/dev/null.

11.5 umask

  • A shell setting subtracted from the defaults: files 666, directories 777. Set in /etc/profile / /etc/bashrc. The first of the four digits (special permissions) is ignored.
umaskFilesDirectories
022 (common)644755
027640750
  • Test: umask, touch file1, umask 007, touch file2, ls -l (others lose all access). Advice: leave the umask alone; the distribution sets it correctly and changes cause hard-to-trace problems.

11.6 Review

chown, chgrp, chmod, umask.

Lab: sales and account directories (needs the lesson 10 users)

sudo mkdir -p /data/sales /data/account
cd /data
sudo chgrp sales sales; sudo chgrp account account
sudo chmod 770 *               # group rw, others nothing
sudo chmod +t *                # delete only own files
sudo chown anna sales          # anna (sales manager) owns the dir, so she can delete all files in it

With the sticky bit a user can delete a file only if they own the file or the directory; making anna the directory owner gives her full control over sales.

Back to top ↑

Lesson 12Storage Management Essentials

Goal: know the storage options, list disks, create partitions (fdisk), file systems (mkfs), mount them and make mounts persistent (/etc/fstab).

12.1 Linux storage solutions

  • Partitions logically separate data on a disk but are inflexible. LVM adds flexibility: partitions become physical volumes β†’ pooled in a volume group β†’ carved into logical volumes that can easily be resized.
  • External storage (SAN/NAS) is reached with iSCSI or Fibre Channel and appears as a local disk.
  • lsblk lists block devices.
Device nameMeaning
/dev/sda, sdbSCSI/SATA disks (a = first, b = second)
/dev/vdaKVM virtual disk
/dev/nvme0n1NVMe: bus 0, node 1 (first disk); nvme0n2 second disk; partitions nvme0n1p1…
/dev/sr0optical drive

12.2 Creating partitions with fdisk

  • fdisk is "the gold standard"; learn one tool well. In the lab VM the disk was enlarged (20β†’30 GB) and a second 20 GB disk added. Disk names can change between boots (the resized disk showed up as nvme0n2), so check lsblk first.
  • Warnings like "GPT PMBR size mismatch" (disk grew) and "disk in use" are expected in the demo.
fdisk keyAction
mhelp menu
pprint the partition table
nnew partition: number, first sector (Enter), size e.g. +2G (uppercase G, case sensitive)
gcreate a new GPT label (on an empty disk)
wwrite changes and exit
qquit without saving
sudo fdisk /dev/nvme0n2
lsblk                   # verify the new partition (e.g. nvme0n2p4)

12.3 Creating file systems

  • A partition needs a file system to store files. Defaults: XFS on Red Hat, ext4 on Ubuntu. (Btrfs exists but isn't covered.) vfat is used for the UEFI system partition (readable by Linux, macOS, Windows) needed for GPT/UEFI boot. NTFS support isn't needed on Linux.
  • Create with mkfs.xfs / mkfs.ext4 (use Tab to list the available mkfs tools). See current ones with mount | grep '^/'.
sudo mkfs.xfs /dev/nvme0n2p4
sudo mkfs.ext4 /dev/nvme0n1p1

12.4 Mounting file systems

  • A mount connects a device to a directory; writes there go to the device. Unmounted β†’ the files aren't visible. /mnt is for temporary mounts; persistent mounts get their own directory.
  • mount DEVICE DIR, umount DIR (umount, not "unmount"). "Target is busy" β†’ you are inside it (cd away) or processes use it: sudo lsof /mnt.
  • Verify with lsblk, df -h, findmnt or mount | grep n2p4. Writing to the mount needs sudo as a normal user.
sudo mount /dev/nvme0n2p4 /mnt
sudo touch /mnt/file
cd; sudo umount /mnt

12.5 Persistent mounts with /etc/fstab

  • /etc/fstab mounts devices at boot (systemd generates mount units from it). Six columns: device, mount point, file system type, options (defaults), dump (0), fsck order (0).
  • Use the UUID, not device names, since names can change. Find it with sudo blkid (quotes around UUID are optional).
# /etc/fstab
UUID=1234-abcd-…   /files   xfs   defaults   0 0

sudo mkdir /files
sudo mount -a          # test: mounts everything in fstab not yet mounted, reports errors
sudo reboot            # ultimate test; then lsblk / mount | grep n2p4
Always run mount -a before rebooting: an invalid fstab line can stop the system booting normally.

12.6 Review

lsblk, fdisk, mkfs, mount, findmnt, umount, lsof, blkid.

Lab: 1 GB ext4 partition, temporary mount

  1. lsblk to identify the new disk, then sudo fdisk /dev/nvme0n1.
  2. If fdisk offers a DOS/MBR label, press g for GPT (MBR allows only 4 primary partitions).
  3. n, partition 1, Enter for the first sector, +1G, w.
  4. sudo mkfs.ext4 /dev/nvme0n1p1
  5. sudo mount /dev/nvme0n1p1 /mnt, verify with lsblk.
Back to top ↑

Lesson 13Managing Networking

Goal: understand IPv4/IPv6 basics, inspect and change runtime network settings with ip, handle device names, host names, name resolution and common network tools.

13.1 IPv4 basics

  • Networks connect through routers; each network has its own network address (e.g. 192.168.0.0/24 = first 3 bytes network, last byte nodes: 192.168.0.1, .2 …). Two networks need a router between them (and each router interface has an address in each network).
  • A node needs three settings: IP address (with mask), default gateway (a router on the local network, often the lowest or highest address, used to leave the network) and DNS server (maps names like google.com to IP addresses).

13.2 IPv6 basics

  • Proposed in the 1990s, still not dominant. Addresses are 128 bits in hex; leading zeros and one run of zeros can be omitted (::). With a port the address goes in square brackets ([fe80::1]:22) because of colons. Default prefix length is /64 (subnetting matters little).
AddressMeaning
::1/128localhost
::unspecified (like IPv4 0.0.0.0, default route)
2000::/3 (2003…)global unicast
fd00::/8unique local (private, not routable)
fe80::/64link-local: assigned automatically, built from the MAC address, not routable
ff00::/8multicast (group packets)
  • Address assignment: static (rare), DHCPv6, or SLAAC: the host sends a router solicitation to the multicast address ff02::2, the router answers with the network prefix (needs the radvd package on the router).
  • You can get far knowing only IPv4.

13.3 Non-persistent (runtime) configuration

  • Servers normally get static addresses via nmcli/nmtui (Red Hat); workstations use DHCP. The ip command changes runtime settings (lost at reboot) and is great for analysis.
  • ifconfig (net-tools) is obsolete and shows inaccurate information; use ip.
ip a                                    # = ip address show
sudo ip addr add 10.0.0.10/24 dev ens160   # add a secondary address
sudo ip link set ens160 down            # disable (bring up again with 'up')
ip route show                           # routing table, shows default route
sudo ip route add default via 10.0.0.1  # changing the default gateway can cut you off

13.4 Network device naming

  • Old names: eth0, wlan0. Modern names (BIOS device names, generated by systemd-udevd) reveal the physical location: eno1 (onboard), ens160 (PCI slot), enp2s0 (PCI bus/slot), em1 (motherboard port). Falls back to ethX if the driver gives too little information.
  • Names are never fixed: check with ip link show (it can show an alternate name such as enp2s0 for ens160).

13.5 Host names

  • Correct host names and resolution matter (reverse lookups are common); slow network behaviour often means broken name resolution.
  • Set the name with hostnamectl hostname NAME (preferred over the old hostname); hostnamectl status shows details. Local resolution: /etc/hosts: IP fqdn shortname.
192.168.29.138   ubuntu.example.org   ubuntu
ping ubuntu

13.6 Host name resolution

  • Order: /etc/hosts first, then DNS servers from /etc/resolv.conf (order set in /etc/nsswitch.conf).
  • systemd-resolved (used on Ubuntu, not installed on the CentOS in the demo): a local caching DNS service. systemctl status systemd-resolved, resolvectl status, configure in /etc/systemd/resolved.conf and restart the service. The DNS shown (e.g. 127.0.0.53 style local stub) is the local cache.

13.7 Common network tools

ToolUse
ping -c4 hostreachability, round-trip time; -c4 sends four packets (otherwise continues)
ss -tulnlistening ports (-n numeric; ss -tul shows service names from /etc/services). Replaces netstat
dig nu.nlDNS lookups (replaces nslookup)
tracerouteall hops to a destination (install first)
nmapnetwork scan: sudo nmap -sn 192.168.29.0/24 finds live hosts; sudo nmap host lists listening ports. Only use on your own systems

13.8 Review

ip a, ip route show, ping, ss, dig, nmap, hostname/hostnamectl.

Lab: verify the network

  1. ip a: interface UP, address dynamic (DHCP), plus IPv6.
  2. ping google.com. If "name or service not known" β†’ DNS problem; then ping 8.8.8.8: if that works but names don't, it is DNS (not routing).
  3. ss -tul (no sudo needed) lists services offered; sudo nmap localhost does the same (only scans common ports).
Back to top ↑

Lesson 14Working with Systemd

Goal: manage services and targets with systemctl, customise unit configuration safely, and handle the no-systemd case (WSL1).

14.1 Understanding systemd

  • The "manager of everything": the first process after the kernel on most distributions (not WSL1). Manages services, mounts, timers, paths, hardware and more. Items it manages are units; learn to manage services first.
  • Key feature: event driven, loading things only when required.

14.2 Managing services

  • systemctl -t help lists unit types; systemctl list-unit-files shows installed unit files and their state (incl. inactive ones); systemctl list-units shows loaded/active units and failures.
  • systemctl status httpd shows: loaded (unit file known, with its path e.g. /usr/lib/systemd/system/httpd.service), enabled/disabled (starts at boot?), preset (package default), active/inactive, PID, memory, and recent journal log lines.
CommandEffect
sudo systemctl start|stop|restart|reload UNITchange the current state
sudo systemctl enable UNITflag for start at boot (does not start it now)
sudo systemctl enable --now UNITenable and start in one go
sudo systemctl disable --now UNITdisable and stop
sudo dnf install -y httpd           # dummy service for the demo
systemctl status httpd              # loaded, disabled, inactive (dead)
sudo systemctl enable --now httpd

14.3 Modifying service configuration

  • systemctl cat UNIT shows the concatenated configuration from all sources (recommended). systemctl show UNIT lists all available parameters.
  • sudo systemctl edit UNIT creates an override file in /etc/systemd/system/UNIT.service.d/override.conf which has higher priority than the packaged unit file, so your settings win. No reload needed. If you edit files directly, run sudo systemctl daemon-reload (but avoid editing directly).
  • Golden rule: if you change the service's own configuration (not the unit file) you must restart it.
sudo systemctl edit httpd
[Service]
Restart=on-failure
RestartSec=20s

sudo systemctl enable --now httpd
sudo kill -9 <MainPID>             # status shows "activating (auto-restart)" and it returns in ~20 s
Auto-restart on failure is one of the best reasons to like systemd.

14.4 Understanding targets

  • A target is a group of units/services. Isolatable targets define the state the system is in. Four to know:
TargetUse
emergency.targetrepair only, minimal
rescue.targetrepair only, more services
multi-user.targetnormal server state, no GUI
graphical.targetworkstation with a desktop
  • systemctl list-dependencies TARGET shows what a target starts (green dot = running, white = not running, red = failed). systemctl get-default / set-default TARGET.

14.5 Managing targets

systemctl get-default
sudo systemctl set-default multi-user.target     # takes effect after reboot
sudo systemctl isolate emergency.target          # switch to a state with fewer services
sudo systemctl start graphical.target            # back to full (or: systemctl isolate default.target)
  • isolate goes from a target with more to one with less. Emergency/rescue need the root account: if root is locked (no password) you can't enter it. Set one beforehand with sudo passwd root (a later lesson shows how to reset a lost root password).

14.6 Services in WSL

  • WSL1 has no systemd; use the old service command (argument order reversed): sudo service vsftpd status. WSL2 uses systemd: systemctl status vsftpd works normally.

14.7 Review

start, stop, restart, status, enable, disable, list-units, get-default/set-default, cat, show, edit, daemon-reload, isolate, list-dependencies, service (non-systemd).

Lab: sshd, default target, active units

  1. systemctl status sshd (works without sudo) and systemctl cat sshd.
  2. Ensure autostart: sudo systemctl enable sshd (was already enabled).
  3. systemctl get-default showed multi-user (left over from the demo); restore with sudo systemctl set-default graphical.target.
  4. Active units: systemctl list-units (better than list-unit-files, which also shows inactive units).
Back to top ↑

Lesson 15Managing Software

Goal: know the ways software is installed on Linux, and use packages, dependencies, DNF/APT, Snap and Flatpak.

15.1 Options for managing software

MethodNotes
Source tarballs (compile)most fundamental, much work, rarely needed now
Plain archivescopy files manually; upgrade/removal is painful
Packagesarchive + metadata, tracked in a local package database: the standard
Software managersinstall packages from repositories and resolve dependencies
Flatpak / Snapnewer: apps in an isolated, container-like environment

15.2 Installing from source

  • Uncompress the tarball (tar), read the README, run the setup script or compile (needs a compiler, gcc, and make). Compiling adapts generic open-source code to your platform.
  • Drawback: no central registration of what you installed, so it's increasingly uncommon.

15.3 Software packages

  • A package is a tarball plus a script to place files and a database entry. Formats: RPM (Red Hat family), DEB (Ubuntu/Debian). Packages declare dependencies.
  • Query the local database:
rpm -qa | grep nmap      # all installed packages (filtered)
rpm -ql nmap             # files in a package
dpkg -l                  # Ubuntu: installed packages

In practice you work with package managers, not the low-level tools.

15.4 Dependencies

  • Dependencies are often libraries (shared common functionality), e.g. libc (the C library, needed by everything) or libpcap (packet capture); or runtimes such as Python for a Python script.
  • ldd $(which passwd) shows the libraries a command uses (libc.so.6, libpam for pluggable authentication, libaudit, libselinux on Red Hat).
  • Only one version of a library can be installed system-wide. To run apps needing different versions, isolate them: containers (lesson 21) or Snap/Flatpak.

15.5 Software managers and repositories

  • Before managers: "dependency hell" (rpm -ivh complains about missing dependencies, which have their own). Managers use repositories (online: packages + an index, provided by the distribution, vendors or yourself).
  • Flow: client (dnf/apt) downloads the latest index β†’ compares with the local database (RPM/dpkg) β†’ resolves dependencies β†’ installs β†’ registers in the local database β†’ knows when updates are due.

15.6 yum / dnf (Red Hat family)

  • DNF replaced yum's backend; with RHEL 10 DNF is no longer backward compatible with yum, so use dnf. Repositories: /etc/yum.repos.d/*.repo.
CommandUse
dnf search zshsearch
sudo dnf install [-y] zshinstall (-y skips confirmation)
dnf list selinux*list installed and available packages; dnf list installed for installed only
sudo dnf updateupdate (consider scheduling)
dnf groups list, sudo dnf groups install "Container Management"package groups; quote names with spaces
dnf provides */selinuxwhich package contains a file
dnf historyreview and undo transactions
dnf repolistenabled repositories

15.7 apt (Ubuntu)

  • apt replaces apt-get / apt-cache in daily use. Repositories: /etc/apt/sources.list plus drop-ins in /etc/apt/sources.list.d/ (files must end in .sources; on Red Hat drop-ins need .repo).
  • Drop-in pattern (common in Linux): main file from the distribution (can be overwritten on update) + name.d/ directory for your own files, which must respect the expected format and extension.
CommandUse
sudo apt updaterefresh the package index first
apt list --upgradable, sudo apt upgradesee / install updates
apt-cache search iotopsearch packages
sudo apt install iotopinstall; services are started and enabled automatically on Ubuntu
sudo apt autoremoveremove no-longer-needed dependencies

15.8 Snap (Ubuntu)

  • Packages run isolated (container tech) with their own dependencies, so different library versions can coexist. From the Snap Store (App Center), which also allows third-party/paid software. Trade-offs: more disk space, slower installs. Some software (e.g. Firefox) is only available as a Snap.
snap list
sudo snap install NAME     # or use the App Center
sudo snap remove NAME
sudo snap refresh          # update all snaps

15.9 Flatpak (Fedora, Red Hat family, others)

  • Distribution-independent alternative to Snap; also isolated, but uses remote repositories (Flathub) instead of a central store. Mostly for desktop applications; a single app can be hundreds of MB because of runtimes.
sudo dnf install flatpak
sudo flatpak remote-add --if-not-exists flathub https://flathub.org/repo/flathub.flatpakrepo
# browse flathub.org, download the .flatpakref, then:
flatpak install ~/Downloads/org.gimp.GIMP.flatpakref
flatpak list

15.10 Review

tar (source), ldd, yum/dnf, apt/apt-cache, snap, flatpak.

Lab: find out whether an FTP server is installed, install one

  • dnf list shows both installed and available packages. Use dnf list installed | grep ftp (or rpm -qa | grep vsftpd) to check what's really installed.
  • Install via the software manager: sudo dnf install -y vsftpd (nmap was already installed earlier).
Back to top ↑

Lesson 16Managing SSH

Goal: harden and run the SSH server (incl. non-default port with firewall and SELinux), understand host keys, and set up key-based login.

16.1 Running the SSH server

  • Install openssh-server (dnf/apt) and make sure it is started and enabled (automatic on Ubuntu, manual on Red Hat). SSH servers on the Internet at port 22 are a common brute-force target.
  • Hardening options in /etc/ssh/sshd_config:
OptionPurpose
Portlistening port (e.g. 2022)
PermitRootLoginconsider disabling direct root login
AllowUsersrestrict who may log in
PasswordAuthenticationallow/disallow passwords (create keys first!)

Running on a non-default port (Red Hat family):

  1. SELinux must allow the port before starting: sudo semanage port -a -t ssh_port_t -p tcp 2022 (check man semanage-port if the options error out).
  2. Edit Port 2022 in /etc/ssh/sshd_config, then sudo systemctl restart sshd (config of the service changed β†’ restart).
  3. Verify: ss -tuln shows 2022; test ssh -p 2022 localhost.
  4. Firewall (firewalld): sudo firewall-cmd --add-port=2022/tcp --permanent, then sudo firewall-cmd --reload; check sudo firewall-cmd --list-all. For the default service: --add-service=ssh --permanent. (Permanent config is separate from runtime config.)

Ubuntu: sudo ufw allow OpenSSH (generic), sudo ufw allow 2022/tcp (custom port). No SELinux step.

16.2 Using the SSH client

  • The server's host key is cached in ~/.ssh/known_hosts on first connect and checked every time; a mismatch makes the connection refused with "REMOTE HOST IDENTIFICATION HAS CHANGED" (possible man-in-the-middle, or just a reinstalled server / recycled IP).
  • Fix when it's legitimate: remove the offending line named in the message, e.g. sed -i 4d ~/.ssh/known_hosts (or ssh-keygen -R host), then reconnect and accept the new key.
  • Non-default port: ssh -p 2022 lisa@webhost; for scp it is uppercase -P.

16.3 Key-based login

  • Passwords can be guessed; a key must be stolen. Steps: create a key pair, copy the public key to the server (the private key stays secret), optionally protect the private key with a passphrase (stolen key is useless without it = multi-factor).
ssh-keygen                       # creates ~/.ssh/id_rsa (private) and id_rsa.pub
ssh-copy-id student@ubuntu       # asks for the password once, installs the public key
ssh ubuntu                       # no password prompt (if no passphrase)
ssh-copy-id -p 2022 host         # option must come before the host here

# avoid typing the passphrase every time (CLI):
eval $(ssh-agent) ; ssh-add      # (in the demo: ssh-agent /bin/bash, then ssh-add)
  • In the GNOME desktop the passphrase prompt offers "automatically unlock this key whenever I'm logged in", so ssh-agent/ssh-add aren't needed there.

16.4 Review

firewall-cmd (Red Hat) / ufw (Ubuntu), semanage port (SELinux), ssh-keygen, ssh-copy-id, ssh-agent, ssh-add.

Lab: SSH server and key login

  1. Install, enable and start the SSH server; test access from another system (a second VM, or localhost).
  2. On the client machine (check which host you're on!) run ssh-keygen (with or without a passphrase), then ssh-copy-id -p 2022 user@host (the -p must be before the host).
  3. Log in again: with a passphrase GNOME offers to cache it for the session.
Back to top ↑

Lesson 17Managing Time

Goal: understand hardware vs system time, set time zones, and configure NTP synchronisation (chrony on Red Hat, systemd-timesyncd on Ubuntu).

17.1 Understanding Linux time

  • Hardware time (BIOS/RTC clock) is the foundation for the system time (software clock) at boot, so a wrong hardware clock gives a wrong system time. Hardware clocks drift, hence NTP (Network Time Protocol) synchronises from the Internet.
  • NTP smooths small differences. If the difference is larger than ~1000 seconds the system refuses to sync (something may be wrong). Fix by setting the system time, then pushing it to the hardware clock: hwclock --systohc.

17.2 Managing Linux time

ToolUse
dateshow time; formatting: date +%d-%m-%Y (%Y four-digit year, %y two-digit; see man date). Can set time, but not the best tool
hwclockhardware clock; --systohc (system β†’ hardware), --hctosys (hardware β†’ system)
timedatectlthe generic tool: show / status, set-time, list-timezones, set-timezone
timedatectl show
timedatectl list-timezones | grep Los
sudo timedatectl set-timezone Africa/Lusaka
sudo timedatectl set-timezone America/Los_Angeles
sudo hwclock --systohc       # after fixing the software clock, if the hardware clock was off

17.3 The NTP protocol: stratum

  • Stratum = reliability/distance from the reference clock: 1 = atomic clock; servers syncing with it are 2; those syncing with stratum 2 are 3, etc.
  • A client talks to several servers, so losing one is no problem. It prefers the most reliable (lowest stratum). If you reach stratum 1 you become stratum 2, so you'd never sync from a stratum 3 server.
  • Local fallback: configure your own server at a high stratum (e.g. 10) so clients on your network can still get time if the Internet is unreachable. Stratum 16 = unreliable, excluded from synchronisation.

17.4 Time sync on Red Hat: chrony

  • Service chronyd, config /etc/chrony.conf (a pool line of Internet servers; add your own with server NAME). Restart after changes. Check with chronyc sources (shows used sources, stratum, offset). A non-existent server simply doesn't appear.
systemctl status chronyd
sudo vim /etc/chrony.conf        # add: server dummy.example.com
sudo systemctl restart chronyd
chronyc sources                  # stratum-1 source with tiny offset = good

17.5 Time sync on Ubuntu: systemd-timesyncd

  • Service systemd-timesyncd, tightly integrated with timedatectl; config /etc/systemd/timesyncd.conf (NTP=, FallbackNTP=, default ntp.ubuntu.com). Restart/reload after edits.
  • A warning "source configuration or drop-ins changed on disk, run systemctl daemon-reload" can't be ignored: do sudo systemctl daemon-reload.
  • timedatectl status should show "System clock synchronized: yes" and "NTP service: active".

17.6 Review

date, hwclock, timedatectl, chronyc.

Lab: show time properties

timedatectl status (readable) or timedatectl show. Note: "NTP service: active" doesn't mean it talks to timesyncd; it is just the generic synchronisation indicator.

Back to top ↑

Lesson 18Process Management

Goal: understand processes and jobs, monitor them with top and ps, change priority with nice/renice, and stop them with kill/killall.

18.1 Processes and jobs

  • Everything that runs is a process with a PID, managed by sending signals (OS-level instructions) with kill. SIGTERM (15) = polite stop; SIGKILL (9) = force stop immediately.
  • Jobs are user processes started from a specific shell.
  • Hierarchy: kernel β†’ systemd (PID 1) β†’ services (daemons, e.g. httpd) and the GUI (gdm β†’ GNOME shell β†’ terminal β†’ bash β†’ your jobs).
  • Multi-threaded processes can be served by several CPUs at once.

18.2 Interactive shell jobs

ActionHow
Start in backgroundcommand &
Suspend a foreground jobCtrl+Z
Resume suspended job in backgroundbg (or bg 1)
Bring job to foregroundfg 1
List jobs of this shelljobs
Interrupt foreground jobCtrl+C
sleep 3600 &
sleep 600 &
jobs
fg 1        # then Ctrl+Z, bg  or Ctrl+C
You can always manage your own jobs without sudo.

18.3 Monitoring with top

  • Line 1: uptime, users, load average (1/5/15 min) = average number of runnable processes. Compare with CPU cores: a 1-core system should stay ≀ 1, a 32-core ≀ 32; higher needs investigation.
  • Press 1 to show each CPU core separately.
  • Tasks line: total / running / sleeping processes.
  • CPU line: id = idle (most interesting), us = user space, sy = system/kernel space (high sy may mean heavy driver activity).
  • Memory: total, free, used, buff/cache (cache = read files kept in RAM; buffers = data waiting to be written to disk). Some of it can be freed, which is why avail Mem is the most useful number.
  • Swap: slower than RAM; kernel parks inactive program memory there.
  • Process list is sorted by CPU; M (uppercase) sorts by memory.

18.4 Managing processes with top

Run top with sudo for management. Test load: sudo dd if=/dev/zero of=/dev/null & a few times.

  • k = send a signal: asks for PID (default = top one) then signal (default 15 SIGTERM).
  • r = renice: PID, then nice value from -20 (highest priority) to +19 (lowest). Negative values need root; normal users can only lower priority of their own processes.
  • Column PR = 20 + NI, e.g. nice 10 β†’ PR 30. q quits.

18.5 Monitoring with ps

CommandMeaning
ps auxall processes, detailed (BSD style; also works as ps -aux)
ps -efSystem V style full listing
ps faxprocess forest: parent/child relations
ps aux --sort=-%mem / --sort pmemsort by memory (ascending = biggest at bottom)
ps -eo pid,args --forestcustom columns
ps -L / -o ... nlwpthreads
  • ps aux | grep sshd also matches grep itself; add | grep -v grep.
  • Columns: USER, PID, %CPU, %MEM, VSZ (virtual), RSS (resident memory, what matters), START, TIME, COMMAND.
  • Pipe into awk, sort, cut to extract what you need.

18.6 Changing priority with nice / renice

nice -n 10 dd if=/dev/zero of=/dev/null &        # friendly: PR 30, NI 10
sudo nice -n -10 dd if=/dev/zero of=/dev/null &  # unfriendly: PR 10, NI -10
ps aux | grep dd
renice -n 19 -p 6685                               # change a running process
sudo killall dd                                    # clean up
Default niceness is 0 for all user processes. Both processes get equal CPU only if priorities are equal.

18.7 Managing processes with kill

  • kill PID sends a signal by PID; killall name by process name.
  • 15 SIGTERM: process can clean up and finish its work. 9 SIGKILL: instant kill, no cleanup (can damage important applications).
  • Rule: always try 15 first; wait; use 9 only if the process still hangs.
kill 7148        # SIGTERM
kill -9 7211     # SIGKILL
killall dd
clear            # clear screen
reset            # rebuild a garbled terminal

18.8 Command review

top, ps, jobs/fg/bg (current shell only), nice, renice, kill, killall, reset.

Lab: managing processes

Task: as root start three dd if=/dev/zero of=/dev/null background jobs, verify them, give one double the CPU, then terminate all.

sudo -i
lscpu
echo 0 > /sys/bus/cpu/devices/cpu1/online   # optional: go down to 1 CPU so priority differences show
dd if=/dev/zero of=/dev/null &   # x3
top                                       # all get ~equal CPU
renice -n -5 -p PID                       # one gets ~double
killall dd
echo 1 > /sys/bus/cpu/devices/cpu1/online # bring the CPU back
Don't jump to -20: it starves everything else. Change in small steps (e.g. -5) and watch the effect.
Back to top ↑

Lesson 19Scheduling Tasks

Goal: choose between cron, systemd timers and at, and schedule recurring and one-time tasks.

19.1 Options overview

ToolUse
cronclassic recurring tasks; crond/cron daemon, edit with crontab -e
atrun a task once in the future; needs atd running
systemd timermodern alternative (Red Hat family uses these a lot); a timer unit managed with systemctl

19.2 cron

  • Check the daemon: systemctl status crond (RHEL) / cron (Ubuntu).
  • /etc/crontab is the historic main file (still has a handy field reference). Five time fields: minute hour day-of-month month day-of-week, then the command.
  • sudo crontab -e -u lynda edits a crontab for a specific user (-e edit, -u user). Without sudo it edits your own; crontab -l lists.
* * * * * logger Greetings from lynda      # every minute (demo only)
sudo journalctl                              # see the logger message in the journal
  • Ubuntu auto-reads /etc/cron.d/ (normal cron syntax, with an extra user field) and /etc/cron.daily|weekly|monthly/ (plain shell scripts, e.g. mandb). CentOS had none by default.
  • Syntax examples: 5-55/10 * * * * = every 10 min from minute 5 to 55; 59 23 * * * = daily 23:59.
To run at 4 pm sharp use 0 16 * * *. * 16 * * * runs every minute from 16:00 to 16:59.

19.3 systemd timers

systemctl list-units -t timer          # active timers
systemctl list-unit-files -t timer     # all available timers
systemctl cat logrotate.timer          # OnCalendar=daily, Persistent=true, RandomizedDelaySec=...
systemctl status logrotate.service     # shows "TriggeredBy: logrotate.timer"
  • A timer triggers a service with the same first name (logrotate.timer β†’ logrotate.service). You activate the timer, not the service.
  • Persistent=true remembers missed runs; RandomizedDelaySec spreads load.

Create your own timer (demo "sander"):

# /etc/systemd/system/sander.service
[Service]
Type=simple
ExecStart=/usr/bin/sleep 60

# /etc/systemd/system/sander.timer  (copied from fstrim.timer as a template)
[Unit]
Description=Sander timer
[Timer]
OnCalendar=weekly
[Install]
WantedBy=timers.target

sudo systemctl daemon-reload
sudo systemctl enable --now sander.timer
Copy an existing unit from /usr/lib/systemd/system into /etc/systemd/system and trim it. Always daemon-reload after editing unit files on disk.

19.4 at: one-time jobs

systemctl status atd
echo "logger hello" | at teatime       # or: at tomorrow, at now + 5 minutes
at -l   (atq)                          # list queued jobs
atrm 3                                 # remove job 3

at accepts very flexible time specifications (see man at).

19.5 Command review

at, atq, atrm, crontab -e, systemctl (timers).

Lab: scheduling tasks

  1. File in 5 minutes: echo "touch /tmp/testfile" | at now + 5 minutes
  2. Run fstrim daily: systemctl cat fstrim.timer (weekly by default) β†’ sudo systemctl edit fstrim.timer and add
    [Timer]
    OnCalendar=daily
    Verify with systemctl status fstrim.timer (shows next trigger). See man systemd.time for time specs.
  3. Hello to syslog at 16:00: crontab -e β†’ 0 16 * * * logger hello
Back to top ↑

Lesson 20Reading Log Files

Goal: know where Linux logs live and how to read them with journalctl and rsyslog files.

20.1 Logging on Linux

  • Syslog: the legacy logging service from Unix days. Modern implementation: rsyslogd, which writes events to files in /var/log.
  • systemd-journald: systemd's own logging service; on some distributions it is the only logger.

20.2 journalctl

Needs root (or journal group) to see everything. Opens in less (space = page, G = end).

CommandShows
journalctlthe whole journal (~70,000 lines in demo)
journalctl -u sshd.serviceone unit (tab completion lists them all)
journalctl -k / dmesgkernel messages only, for kernel-related troubleshooting
journalctl -u crond --since yesterday --until nowtime range filter
journalctl -p infopriority info and above (lots)
journalctl -p errerrors only: most useful when troubleshooting
journalctl -xbb = current boot, x = explanations (extra help lines for common failures)
Journal is not persistent by default. /etc/systemd/journald.conf has Storage=auto: if /var/log/journal exists the journal is stored persistently. Create it, then systemctl restart systemd-journald or journalctl --flush (systemctl start systemd-journal-flush) to apply without rebooting.

20.3 rsyslog

  • Works with facility (what to look for, e.g. auth, cron, kern), priority (severity) and destination (usually a file).
  • Main config /etc/rsyslog.conf (skip the modules part, look at RULES). On CentOS:
    • kern.* /dev/console
    • *.info;mail.none;authpriv.none;cron.none /var/log/messages: main log file
    • authpriv.* /var/log/secure: authentication
  • Log files are plain text: read with sudo less /var/log/messages (G = bottom), tail -f to monitor live, plus the usual text tools (grep etc.).
  • To filter by error priority only in a specific file you must tweak the rsyslog configuration.
Ubuntu spreads rules over drop-ins: /etc/rsyslog.d/50-default.conf. There auth,authpriv.* /var/log/auth.log, so authentication messages are in /var/log/auth.log (RHEL: /var/log/secure).

20.4 Command review

journalctl, tail (monitor /var/log/messages), less, and logger which writes a message to the current logging system (works with rsyslog and journald), e.g. logger "hello".

Lab: find where authentication messages are logged

systemctl status rsyslog
sudo vim /etc/rsyslog.conf        # no rules? check drop-ins
ls /etc/rsyslog.d/
sudo less /var/log/auth.log       # Ubuntu (CentOS/RHEL: /var/log/secure)
Back to top ↑

Lesson 21Containers and Linux

Goal: understand what a container is and run and manage containers with Docker or Podman.

21.1 What is a container?

  • Definition: an application started from a container image in an environment isolated by Linux kernel namespaces.
  • Namespaces: kernel-level isolation, so only files, users and processes relevant to the container are visible; the app can't "go up" into the host OS.
  • Image: contains all dependencies, so no dependency problems. Obtained from a container registry (online repository).
  • No kernel inside the container: it uses the host kernel.
  • Host needs a container runtime (starts containers: containerd, CRI-O) and a container manager (Docker, Podman). Installing the manager brings the runtime.
  • Standardised by the OCI (Open Containers Initiative): same image runs on a laptop, a distributed platform or the cloud. That's why containers became the de facto standard.

21.2 Docker or Podman

  • Docker started the revolution in 2014. Podman arrived in RHEL in 2018 and is the default on the Red Hat family. Its CLI is fully compatible: replace docker with podman (or alias docker=podman).
  • Red Hat family: Podman is available by default; Docker is not supported. Ubuntu: sudo apt install docker.io or sudo apt install podman.
  • Registries: Docker Hub (hub.docker.com) is the biggest, useful for Podman users too (usage docs for each image). docker login REGISTRY if needed.
docker search nginx
docker run -d nginx                    # -d = background; image is pulled first (layers)
docker run -it ubuntu bash             # interactive terminal
docker run -d docker.io/library/nginx  # fully qualified container name (FQCN), preferred on Podman
docker ps                              # running containers
docker images                          # downloaded images
On Ubuntu a normal user must be in the docker group, otherwise "permission denied ... Docker daemon":
sudo usermod -aG docker student
newgrp docker      # activate now (or log out/in)

21.3 Managing containers

Arguments for docker run go before the image name, never after it.

NeedOption
Port forwarding (host:container)-p 8080:80 then curl localhost:8080
Persistent storage (bind mount)-v /home/student/web:/var/lib/mysql
SELinux (Red Hat family)append :z to the bind mount: -v /web:/var/lib/html:z
Environment variables-e MARIADB_ROOT_PASSWORD=password
docker run -d -p 8080:80 nginx
docker run -d mariadb                  # fails to start: not shown in docker ps
docker ps -a                           # shows failed containers too
docker logs NAME_OR_ID                 # reason: root password option not specified
docker run -d -e MARIADB_ROOT_PASSWORD=password mariadb
docker run -d -e MARIADB_ROOT_PASSWORD=password -v /home/student/web:/var/lib/mysql mariadb
docker inspect NAME_OR_IMAGE           # parameters used to start it
Container data is not persistent by default: delete the container and the data is gone. A bind mount keeps data on the host (the demo showed MariaDB files appearing in ~/web).

21.4 Command review

podman / docker, search, run, ps, inspect, logs, images.

Lab: run an application as a container

podman search redis                       # find the FQCN
podman run -d docker.io/library/redis
podman ps                                 # redis running
Back to top ↑

Lesson 22Managing the Kernel

Goal: understand the kernel's role, the boot process and rescue modes, how drivers are loaded, and how to inspect/tune the kernel via /proc.

22.1 Understanding the kernel

  • The kernel is needed to use hardware: core OS components, dynamically loaded drivers, and it ensures security, stability, performance.
  • Responsibilities: processes, memory management, file system management, device management, networking, interrupt handling, hardware communication.
  • System space (kernel space): privileged, unrestricted; kernel + drivers (kernel modules). User space: restricted, where applications run.
  • Applications reach the kernel via system calls (deep-level instructions, visible via the audit subsystem).

22.2 How Linux boots

  1. GRUB (Grand Unified Bootloader): has a shell, useful to influence boot.
  2. Kernel loaded together with initrd/initramfs (essential drivers).
  3. systemd: early boot (essential system components), then services, then a shell/login.

From the GRUB menu add kernel parameters for troubleshooting:

ParameterEffect
systemd.unit=emergency.targetjumps in right before early boot: minimum services, hardcore troubleshooting
systemd.unit=rescue.targetafter early boot: more of the normal system available, easier to fix
systemd.unit=multi-user.targetcomplete operational environment (no GUI)
systemd.unit=graphical.targetnormal graphical boot

22.3 Entering boot parameters

  • Press Esc at the right moment during boot (watch for the cursor) to get the GRUB menu. If it fails, reset the machine during boot: after an unsuccessful boot the GRUB menu shows automatically.
  • Select entry, press e to edit. The line starting with linux loads the kernel (vmlinuz). Append parameters (remove rhgb quiet / quiet splash to see boot messages). Ctrl+X boots.
  • Boot arguments are not persistent; used for troubleshooting.
RHEL/CentOS: emergency/rescue target runs sulogin, so the root password must be set, otherwise it fails.
Ubuntu: root has no password by default but it works anyway: "Press Enter for maintenance" gives a root shell (no sulogin).

22.4 How drivers are loaded

  • At install an initrd / initramfs image is generated with drivers for essential hardware detected at install time; kernel loads it at boot.
  • Other hardware is handled by systemd-udevd, the plug-and-play manager (at boot or when hardware is connected).
  • Drivers = kernel modules.
CommandUse
lsmodloaded kernel modules
lspci -kPCI devices with the kernel module in use (e.g. Ethernet controller β†’ e1000e; VGA β†’ vmwgfx)
lsusbUSB bus and devices
modprobe NAMEload a module manually (rarely needed)
modprobe -r NAMEremove a module

Most devices have open-source modules in the kernel; some (e.g. NVIDIA GPUs for AI) need the proprietary driver.

22.5 The /proc filesystem

A pseudo file system: an interface to kernel settings, not stored on disk. Three main kinds of content:

  • Status files, e.g. /proc/meminfo, /proc/cpuinfo
  • /proc/sys: kernel tunables, grouped in subdirectories (e.g. vm)
  • /proc/PID/: one directory per process (cmdline = the command, empty for kernel processes; status = detailed info)
cat /proc/sys/vm/swappiness          # 30 (0-100: higher = swaps sooner)
echo 60 > /proc/sys/vm/swappiness   # only way to change: write into the file (as root)
cat /proc/949/cmdline                # udisksd
cat /proc/949/status
Changes via echo are not persistent across reboots (they're made in the running kernel).

22.6 Command review

systemd-udevd, modprobe, lsmod, lspci, lsusb.

Lab: boot parameters (emergency vs rescue)

  1. Reboot, edit GRUB entry (e), remove rhgb quiet, add systemd.unit=emergency.target, boot with Ctrl+X, enter the root password.
  2. systemctl list-units shows ~98 units, mostly devices and only essential services.
  3. systemctl start rescue.target to move on: more units (mounts, more services).
  4. reboot to return to normal mode. (Rescue shows fewer units in some respects because emergency addresses devices differently, aiming to give access to all hardware.)
Back to top ↑

Lesson 23Managing Hardware

Goal: trace hardware events with udev, list hardware and its properties, understand CPU architecture, and install a proprietary driver.

23.1 systemd-udevd (plug-and-play manager)

  • Standard component that makes plugged-in hardware available with the right properties by processing rules:
    • /usr/lib/udev/rules.d/: standard rules from packages, don't modify
    • /etc/udev/rules.d/: your own rules (advanced)
  • sudo udevadm monitor traces events live when you plug/unplug a device (e.g. a USB drive: device initialised as sda/sda1, exfat module loaded). Great for troubleshooting "nothing happens when I plug it in".
  • Device paths like /devices/pci0000:00/... refer to the /sys filesystem, the basis of all hardware management.

23.2 Listing hardware

CommandLists
sudo lshw | lesseverything (very detailed; run as root; use specific tools for specific needs)
lscpuCPU details (merges /proc/cpuinfo with more): model, cores, cache
lsblkblock devices (disks, removable media)
lspci / lspci -kPCI devices / with kernel modules used
lsusbUSB devices
lsmemmemory configuration; interesting with NUMA (non-uniform memory access) topology
lsinitrdcontents of the initrd image (directory structure and drivers), to check whether a driver is included
Not all of these are installed by default on every distribution.

23.3 Hardware properties

  • Properties live in /sys, but it's complicated; use udevadm info: sudo udevadm info /dev/cdrom shows all properties (and the underlying /sys/devices path).
  • modinfo MODULE shows driver info and its parameters. Find the module first: lsmod | grep sr β†’ modinfo cdrom. For a NIC (e.g. e1000) parameters such as duplex show how the card works. Driver parameter problems can cause hardware issues.

23.4 CPU architecture

  • Architecture defines how instructions execute. Intel/AMD = CISC (x86_64), ARM = RISC (aarch64). Instruction sets are incompatible, so programs must be compiled for your architecture.
  • Wrong architecture gives cannot execute binary file: Exec format error.
arch                 # aarch64 / x86_64
uname -r             # kernel version also shows the architecture
file $(which zombie) # ELF 64-bit ... x86-64   (wrong on ARM)
file /usr/bin/passwd # ... ARM aarch64

Most mainstream Linux software exists for both; externally obtained programs may occasionally fail on ARM.

23.5 Command review

arch, uname -r, lshw, lscpu, lsblk, lspci, lsusb, lsmem, lsinitrd, modinfo, udevadm.

Lab: replacing a video driver (physical machine, watch-along)

Goal: replace the open-source driver with the vendor's official one (NVIDIA L4 GPU on Fedora).

  1. lspci -k shows the 3D controller using the nouveau driver. AI work needs CUDA, which nouveau doesn't provide.
  2. Enable RPM Fusion (free + non-free repos; accept the GPG key).
  3. dnf install akmod-nvidia xorg-x11-drv-nvidia-cuda (~0.5 GB; includes CUDA). On modern Fedora akmods --force is not needed.
  4. dracut --force to rebuild the initramfs so the new driver is available at boot, then reboot.
  5. Verify: lspci -k shows nvidia, nvidia_drm; nvidia-smi shows the GPU. Bonus: dnf install nvtop for GPU activity.
For proprietary drivers there is no universal recipe: research the vendor's procedure for your driver and distribution.
Back to top ↑

Lesson 24Linux Security

Goal: configure firewalls (firewalld / ufw) and understand mandatory access control with SELinux (Red Hat) and AppArmor (Ubuntu).

24.1 Firewalls

Filtering incoming traffic, implemented in the kernel. Red Hat: firewalld, Ubuntu: ufw (Uncomplicated Firewall). Completely different tools.

firewalld (firewall-cmd)

  • Distinguishes runtime vs permanent configuration. Add --permanent to survive reboot, then --reload to activate. Permanent changes don't affect the running config until reload.
sudo firewall-cmd --list-all
sudo firewall-cmd --get-services
sudo firewall-cmd --add-service=http --permanent
sudo firewall-cmd --reload
sudo firewall-cmd --add-port=82/tcp --permanent

ufw

sudo ufw status             # inactive at first
sudo ufw enable
sudo ufw allow ssh          # service names come from /etc/services
sudo ufw reject out ssh     # outgoing rule (inconvenient, so delete it)
sudo ufw delete reject out ssh
sudo ufw reset              # start over
sudo ufw app list           # application profiles (more complex config)
sudo ufw app info Cups
sudo ufw logging on

24.2 Mandatory Access Control (MAC)

  • Optional security layer using Linux kernel security modules: restricts access based on policies/profiles. Needed because Linux security wasn't designed with one overall perspective.
  • Independent of normal permissions and both apply: MAC can't grant what permissions deny.
  • Locks the system down: only explicitly allowed behaviour is allowed, which protects even against zero-day exploits (unknown flaws).
  • Two frameworks: SELinux (Red Hat family), AppArmor (Ubuntu).

24.3 SELinux

  • Works with context labels on processes and files; the policy defines which process types may access which file types. E.g. process type httpd_t may access files labelled httpd_sys_content_t (document root /var/www/html).
  • Denials go to the audit log: sudo grep AVC /var/log/audit/audit.log. Also check sealert messages in the logs (sudo grep sealert /var/log/messages), which suggest fixes. Read the explanation, it's sometimes good, sometimes not.
CommandUse
getenforceshow mode (Enforcing / Permissive / Disabled)
setenforce 0|1Permissive/Enforcing, temporary (until reboot), to test whether SELinux is the problem
ps auxZ, ls -Z, ls -dZ /webshow contexts (the t part, the type, matters)
semanage fcontext -a -t TYPE 'PATH(/.*)?'define a file context in the policy
restorecon -Rv PATHapply the policy context to the file system
semanage port -a -t http_port_t -p tcp 82allow a service to bind a non-standard port

Demo: Apache with a custom document root

  1. Edit /etc/httpd/conf/httpd.conf: DocumentRoot "/web" and the matching <Directory> block.
  2. mkdir /web; echo hello | sudo tee /web/index.html; systemctl restart httpd; curl localhost still shows the default page.
  3. ls -dZ /web β†’ default_t. The policy allows httpd_t β†’ httpd_sys_content_t, not default_t (that would open Apache to everything).
  4. AVC denial in audit log confirms it (source httpd_t, target default_t).
  5. Fix (command found in man semanage-fcontext, in its examples):
    sudo semanage fcontext -a -t httpd_sys_content_t "/web(/.*)?"
    sudo restorecon -Rv /web
    curl localhost       # works
The (/.*)? is a regular expression so the context applies to /web and everything inside. Always look at the end of man pages for examples.

24.4 AppArmor

  • Ubuntu's MAC. sudo aa-status shows loaded profiles (enforce mode). Profiles are in /etc/apparmor.d/, named after the full path of the protected program (e.g. usr.bin.vim.basic). Only programs with a profile are protected; others can do anything.
CommandUse
apparmor_parser -a FILE / -r FILEload / reload (replace) a profile
aa-genprof PROGRAMgenerate a profile (package apparmor-utils)
aa-complain PROFILElogging-only mode, for tuning
aa-enforce PROFILEback to enforcing

Demo: profile for vim

  1. sudo apt install apparmor-utils; sudo aa-genprof vim
  2. In another terminal use the program as fully as possible (demo: vim /etc/motd, edit, save).
  3. Back in aa-genprof press S to scan events; for each, choose Allow or Glob (e.g. allow writes to everything in /etc) etc.; S save, F finish.
  4. sudo aa-status | grep -C5 vim shows the new profile. Now writing to a file in /root fails with "can't open file for writing": the profile is doing its job.
  5. Inspect/tune /etc/apparmor.d/usr.bin.vim.basic (allows home read, /etc read/write). In real life keep iterating until it fits.

24.5 Command review

firewall-cmd, ufw, getenforce/setenforce, sealert, semanage, restorecon, aa-status, apparmor_parser, aa-complain, aa-enforce.

Lab: Apache on port 82 with firewall and MAC (Red Hat)

sudo dnf install httpd
sudo vim /etc/httpd/conf/httpd.conf             # Listen 82
man semanage-port                               # examples near the end
sudo semanage port -a -t http_port_t -p tcp 82  # SELinux allows binding port 82
sudo firewall-cmd --add-port=82/tcp --permanent
sudo firewall-cmd --reload
sudo systemctl restart httpd
sudo systemctl status httpd                     # listening on 82
The lab also asks for port 80 in the firewall: firewall-cmd --add-service=http --permanent. On Ubuntu: package apache2, ufw allow 80/tcp, and AppArmor needs no extra port step.
Back to top ↑

Wrap-upCourse summary

You've covered Linux from installation and the shell through files, users, permissions, storage, networking, systemd, software, SSH, time, processes, scheduling, logging, containers, kernel, hardware and security.

Next steps: certification paths by the instructor: RHCSA (Red Hat), LFCS and Linux+ (distribution-independent).

Back to top ↑

No lesson matches that search.