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.
| Family | Members 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. |
1.4 Installing Red Hat family (CentOS Stream demo)
- Download from
centos.org(CentOS Stream) ordevelopers.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.comis 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(ort2.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
.pemfile locally and usessh -ilater). 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). Tryfree -manddf -h.
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.
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,qorquit), 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 --helpprints a usage summary. Some options exist only in short form (-l), others in both (-k/--kibibytes).
2.4 Seven essential tools
| Command | What it does |
|---|---|
whoami | Show your username |
pwd | Print working directory (the prompt shows ~ for your home) |
ls / ls -a | List files; -a includes hidden files (names starting with a dot, a convention only) |
touch file | Create an empty file, handy to test whether you can write in a directory |
cat file | Display a text file (e.g. cat ~/.bashrc, a startup file) |
passwd | Change your password (admins can change others'). Errors such as "authentication token manipulation error" mean it failed, e.g. new = old |
ip a | Show 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 |
$ 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:
/textsearch,nnext match, space page down,qquit. The header shows the command in uppercase for historical (typewriter) reasons. infois a clunky alternative (menus with*,Enterto follow,uup,qquit). You can work with Linux without it.
2.6 Finding the right man page
- Pages are indexed in the mandb.
man -k keyword(same asapropos 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β findsuseradd, thenman 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
man -k hostnamesearches descriptions too β hostnamectl (section 1/8). Set it withhostnamectl hostname linfen.example.org. Open a new terminal (exitand reopen) to see the new name; config changes often need a restart of the thing reading them, not the whole system.ip helpβip link help(help flag errors, but still prints help). Find the device withip link show.sudo ip link set ens160 down; without sudo you get "operation not permitted". Bring it back withsudo ip link set ens160 up.
Ctrl+A jumps to the start of the command line (to add sudo in front of the previous command).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.
termfor Terminal,powerfor 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
termand 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
- Log out via power menu β Log Out, then log back in through GDM.
- Disable screen saver / blanking in Settings (Power).
- 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.
- Behavior β Bell: disable the audible bell (beep on mistakes) and the visual bell.
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 /thentreeshows the layout; some entries are symlinks (shown withls -l); colours depend on terminal settings, ignore them.
| Directory | Purpose |
|---|---|
/boot | Everything needed to boot, incl. the kernel (vmlinuz-6.12β¦) |
/dev | Device files to talk to hardware (e.g. disk nvme0n1) |
/etc | Configuration files, e.g. /etc/os-release (distribution info) |
/home | Users' own environments |
/proc | Live view into the kernel, e.g. /proc/cpuinfo |
/usr | Program 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 |
/var | Dynamically 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
-ahidden files,-llong listing,-dshow the directory itself not its contents,-tsort by time (newest first),-rreverse.ls -lrtputs the most recently modified file last.- Columns of
ls -l: type character (ddirectory,-file,llink) Β· 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)
| Pattern | Matches |
|---|---|
* | 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} |
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: ifdestdoesn'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.-Rrecursive (copy directories),-aarchive (keeps attributes, includes hidden files). For complete directory copies,tar(covered later) is better..= current directory:cp /etc/hosts .
4.5 Working with directories
cdwith no argument goes home.mkdir dircreates;mkdir -p a/b/ccreates the whole path (without-pit fails if the parent is missing).rmdironly removes empty directories;rm -rfworks with content.- As a normal user
mkdir /datais denied; usesudo.
4.6 Absolute and relative paths
- Absolute: from root, always unambiguous (
/var/log/messages). Relative: from the current directory (log/messageswhen in/var;./log/messagessame thing)...= one directory up (from/var/empty:../log/messages). - Advice: use absolute paths to avoid confusion.
4.7 Moving with mv
mvmoves 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 -iasks for each file;rm -fforce without asking;rm -rf dirremoves 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
- Create the tree in one go:
cd /tmp; mkdir -p files/pictures files/photos files/videos; check withtree files. - 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). cd files; mv [ab]* photos/; mv c* videos/then verify withtree.
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/sbinare symlinks. Old FHS put boot-critical files in/bin; that requirement was dropped, but scripts referencing/bin/passwdmust 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
sudoto avoid "permission denied" noise. -nameis 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 ffiles 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
-execblocks can be chained, each closed with\;(missing one gives "missing argument to -exec"). 2>/dev/nullsuppresses error messages.;separates two commands on one line (create the target dir first).-printfformats 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 1feeds 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.
ccreate,xextract,tlist,vverbose,ffile name. Extraction goes to the current directory; use-C pathto change it. - Compression flags:
zgzip,jbzip2,Jxz. Listing/extracting detects compression automatically. - Options work with or without a dash (BSD style
tar cvfvs System V styletar -cvf);tarandpshonour BSD origins. - Reading
/etcfully 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./bootis usually its own mount; a USB stick mounts dynamically (e.g./run/media/student/β¦).
| Command | Shows |
|---|---|
lsblk | Block devices and mount points (clear overview; disk nvme0n1, optical sr0, USB sda) |
mount | All mounts incl. many internal ones; filter: mount | grep '^/' (only real devices) |
df -h | Mounted devices with free space |
findmnt | Tree 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
- Files under 1000 bytes in /etc β /tmp/files/pictures.
man findβ-size:+n,-n(less than), suffixc= bytes.mkdir -p /tmp/files/pictures; sudo find /etc -type f -size -1000c -exec cp {} /tmp/files/pictures \; - Symlink to /var in /tmp/files:
cd /tmp/files; ln -s /var .(target first, then where). - Compressed archive of /home:
sudo tar -czvf home.tgz /home(.tgz= tar+gzip; needs sudo to read other homes). - Extract with relative names into /tmp/archive:
mkdir ../archive; sudo tar -xvf home.tgz -C ../archive; check withtree. - Clean up with relative names (
rm -rf archive etc filesin /tmp), usingsudoper command. Avoid opening a root shell: one careless command can damage the system.
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 withsudo 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 / command | Meaning |
|---|---|
:wq! | write, quit, don't complain. ZZ (shiftβZZ) = write and quit |
:q! | quit without saving ("desperate mode") |
u / Ctrl+R | undo / redo |
dd, 3dd | delete current line / 3 lines |
:%s/old/new/g | global substitute (without g, only the first match per line) |
v, d, y | visual mode select, delete, yank (copy) |
/text | search |
gg / G | top / bottom of file |
w / b | next / previous word |
^ / $ | start / end of line |
dw | delete a word |
O / o | open a line above / below |
:set number | show line numbers |
r | replace one character |
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,^/$,dwthenu,Oto 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.
lessis the default and the engine behindman(same keys:/search,q).moreoriginally 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/messagesfollows new lines live (stop with Ctrl+C,qdoesn't work).
6.6 cat and tac
cat -Ashows nonβprinting characters ($= end of line),-nnumbers all lines,-bnumbers nonβempty lines,-ssqueezes repeated blank lines.tacprints the file in reverse order.
6.7 grep
- Searches text or regular expressions in files or piped output (more in lesson 7).
| Option | Effect |
|---|---|
-i | ignore case |
-v | invert: lines that do not match |
-l | list only file names |
-r | recursive (needed for directories) |
-A5 / -B5 / -C5 | 5 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
vim usersβ i, type lines such as Anna, Annabelle, Anna Bell, banana, Esc,ZZ. (Reused in lesson 7 for regular expressions.)grep Anna users- Last line only:
tail -1 users - Reverse order:
tac users
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).cutneeds a delimiter (-d) and a field (-f). sortis alphabetical by default (1, 10, 2β¦);sort -nsorts 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.
| Pattern | Meaning / example |
|---|---|
^ $ | anchors: start / end of line ('^an', 'ana$') |
. | any single character; '^.$' = lines with exactly one character |
\< \> / \b | word 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:]overa-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;-Fsets 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+pprints a line;-iedits the file in place;s/old/new/gsubstitutes;Nddeletes line N without opening the file (handy when a tool complains about "error on line N"). - Combine with a shell
forloop; 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
- Delete the 5th line of
users:sed -i 5d users - First column of
ps aux:ps aux | awk '{ print $1 }' - Files in /etc with lines starting with "root":
sudo grep -ril '^root' /etc(-lnames only,-rrecursive,-iignore case) - 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) - Lines ending in "ana":
grep 'ana$' users
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 lisaopens a subshell as lisa (needs lisa's password unless you are root).sualone = root shell (root's password).- A plain
sukeeps much of your environment. Usesu -(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 -iopens a root shell (prompt ends in#); use only when you know many privileged commands follow, andexitafterwards.- Redirects and pipes are handled by your current shell, so
sudo echo hello >> /var/log/messagesfails. 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 withsudo 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: ALLworks but is insecure, avoid it. - Lengthen the password cache:
Defaults timestamp_type=global
Defaults timestamp_timeout=240 # minutes (4 hours)
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
sshon Linux/macOS; on Windows use e.g. MobaXterm. By default it tries your local user name; usessh user@hostotherwise. 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 >> fileredirects 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
sudo visudo, then addDefaults timestamp_type=globalandDefaults timestamp_timeout=240; save.- It takes effect only after the current token (5 min) expires; the next password entry is then valid for 4 hours.
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 / operator | Use |
|---|---|
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) |
| pipe | output of one command is input of the next (ps aux | grep http) |
tee | sends 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_historywhen the session closes.
| Command | Effect |
|---|---|
history | list; -c clear, -w write now, -d N delete line N (e.g. a mistyped clear-text password) |
| Ctrl+R | reverse search anywhere in a command; press again for older matches |
!416 | repeat 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.envlists the environment. - Set:
COLOR=red. By default only the current shell knows it;export COLOR=redmakes it available in subshells (test withbash, thenecho $COLOR,exit).
9.6 Other bash features
- alias:
alias list='ls -l'; plainaliaslists 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
| File | When / purpose |
|---|---|
/etc/environment | list of variables, first processed (empty on Red Hat) |
/etc/profile | system-wide, at login; a complex script, treat as read-only |
/etc/profile.d/*.sh | drop-in directory: put custom .sh files here (.csh files are ignored by bash) |
/etc/bashrc | system-wide, read every time a (sub)shell starts |
~/.bash_profile, ~/.bashrc | per-user versions of the above |
~/.bash_logout | runs 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:
ipconfigworks andecho $COLORshows red (it beats green fromcustom.shbecausesander.shsorts aftercustom.sh).
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/nologinso 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 -lshows linda:linda.
10.3 Creating users with useradd
sudo useradd anna. On Ubuntu useuseradd -mto get a home directory (Red Hat creates one by default).adduseralso exists; pick one command and stick to it.- Defaults come from
/etc/login.defs(change it before creating users; existing users aren't updated) anduseradd -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-aGto append.
10.5 User and group properties
/etc/passwdfields: 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/passwdorgetent passwd anna.getentalso queries external sources such as LDAP, which is why it's useful in central-authentication environments.- Passwords are in
/etc/shadow. Change generic properties withusermod, passwords withpasswd. - Groups are in
/etc/group; secondary memberships are recorded there (passwd has room for only one group). Useidto 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 usepasswdandchage(change ageing).chage -l userlists; plainsudo chage lindaprompts for each setting (recommended overpasswd -x/-n/-w).
| chage setting | Meaning |
|---|---|
| Minimum | days before the password can be changed again (e.g. 3) |
| Maximum | days until it must change (e.g. 30) |
| Warning | days of warning before expiry (e.g. 1) |
| Inactive / Expire | days after expiry until the account locks / absolute account expiry date |
- Values are in
/etc/shadowas 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; useecho 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) andw(also shows what each user is doing).sudo chvt 6switches to virtual terminal 6 (back withsudo 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).
Lesson 11Permissions Management
Goal: control access with basic permissions (rwx), special permissions (SUID, SGID, sticky bit) and umask.
11.1 Basic permissions
| Permission | Octal | On a file | On a directory |
|---|---|---|---|
| r read | 4 | read content | list contents (ls) |
| w write | 2 | modify content | add / remove files |
| x execute | 1 | run it (if executable) | enter it (cd) |
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
/home/anna.11.3 Advanced permissions
| Permission | Octal | Effect |
|---|---|---|
| SUID set user ID | 4 | Files only: runs as the file's owner. Dangerous; avoid except where needed |
| SGID set group ID | 2 | Files: run as group owner (rare). Directories: new items inherit the directory's group owner |
| Sticky bit | 1 | Directories: 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/saleswould be group-owned by linda. Set SGID:sudo chmod g+s /data/sales; new files become group sales. Check withls -ld: showsrwsin 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
xposition. Lowercases/t= special bit plus execute; uppercaseS/T= special bit without execute (e.g.drwxrws---Tstyle output when others have no x). - SUID example:
/usr/bin/passwdis-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.
| umask | Files | Directories |
|---|---|---|
| 022 (common) | 644 | 755 |
| 027 | 640 | 750 |
- 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.
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.
lsblklists block devices.
| Device name | Meaning |
|---|---|
/dev/sda, sdb | SCSI/SATA disks (a = first, b = second) |
/dev/vda | KVM virtual disk |
/dev/nvme0n1 | NVMe: bus 0, node 1 (first disk); nvme0n2 second disk; partitions nvme0n1p1β¦ |
/dev/sr0 | optical 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 checklsblkfirst. - Warnings like "GPT PMBR size mismatch" (disk grew) and "disk in use" are expected in the demo.
| fdisk key | Action |
|---|---|
m | help menu |
p | print the partition table |
n | new partition: number, first sector (Enter), size e.g. +2G (uppercase G, case sensitive) |
g | create a new GPT label (on an empty disk) |
w | write changes and exit |
q | quit 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 withmount | 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.
/mntis 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,findmntormount | 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/fstabmounts 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
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
lsblkto identify the new disk, thensudo fdisk /dev/nvme0n1.- If fdisk offers a DOS/MBR label, press
gfor GPT (MBR allows only 4 primary partitions). n, partition 1, Enter for the first sector,+1G,w.sudo mkfs.ext4 /dev/nvme0n1p1sudo mount /dev/nvme0n1p1 /mnt, verify withlsblk.
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).
| Address | Meaning |
|---|---|
::1/128 | localhost |
:: | unspecified (like IPv4 0.0.0.0, default route) |
2000::/3 (2003β¦) | global unicast |
fd00::/8 | unique local (private, not routable) |
fe80::/64 | link-local: assigned automatically, built from the MAC address, not routable |
ff00::/8 | multicast (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 theradvdpackage 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
ipcommand changes runtime settings (lost at reboot) and is great for analysis. ifconfig(net-tools) is obsolete and shows inaccurate information; useip.
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 toethXif the driver gives too little information. - Names are never fixed: check with
ip link show(it can show an alternate name such asenp2s0forens160).
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 oldhostname);hostnamectl statusshows 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/hostsfirst, 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.confand restart the service. The DNS shown (e.g. 127.0.0.53 style local stub) is the local cache.
13.7 Common network tools
| Tool | Use |
|---|---|
ping -c4 host | reachability, round-trip time; -c4 sends four packets (otherwise continues) |
ss -tuln | listening ports (-n numeric; ss -tul shows service names from /etc/services). Replaces netstat |
dig nu.nl | DNS lookups (replaces nslookup) |
traceroute | all hops to a destination (install first) |
nmap | network 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
ip a: interface UP, address dynamic (DHCP), plus IPv6.ping google.com. If "name or service not known" β DNS problem; thenping 8.8.8.8: if that works but names don't, it is DNS (not routing).ss -tul(no sudo needed) lists services offered;sudo nmap localhostdoes the same (only scans common ports).
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 helplists unit types;systemctl list-unit-filesshows installed unit files and their state (incl. inactive ones);systemctl list-unitsshows loaded/active units and failures.systemctl status httpdshows: 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.
| Command | Effect |
|---|---|
sudo systemctl start|stop|restart|reload UNIT | change the current state |
sudo systemctl enable UNIT | flag for start at boot (does not start it now) |
sudo systemctl enable --now UNIT | enable and start in one go |
sudo systemctl disable --now UNIT | disable 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 UNITshows the concatenated configuration from all sources (recommended).systemctl show UNITlists all available parameters.sudo systemctl edit UNITcreates an override file in/etc/systemd/system/UNIT.service.d/override.confwhich has higher priority than the packaged unit file, so your settings win. No reload needed. If you edit files directly, runsudo 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
14.4 Understanding targets
- A target is a group of units/services. Isolatable targets define the state the system is in. Four to know:
| Target | Use |
|---|---|
emergency.target | repair only, minimal |
rescue.target | repair only, more services |
multi-user.target | normal server state, no GUI |
graphical.target | workstation with a desktop |
systemctl list-dependencies TARGETshows 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)
isolategoes 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 withsudo 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
servicecommand (argument order reversed):sudo service vsftpd status. WSL2 uses systemd:systemctl status vsftpdworks 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
systemctl status sshd(works without sudo) andsystemctl cat sshd.- Ensure autostart:
sudo systemctl enable sshd(was already enabled). systemctl get-defaultshowed multi-user (left over from the demo); restore withsudo systemctl set-default graphical.target.- Active units:
systemctl list-units(better thanlist-unit-files, which also shows inactive units).
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
| Method | Notes |
|---|---|
| Source tarballs (compile) | most fundamental, much work, rarely needed now |
| Plain archives | copy files manually; upgrade/removal is painful |
| Packages | archive + metadata, tracked in a local package database: the standard |
| Software managers | install packages from repositories and resolve dependencies |
| Flatpak / Snap | newer: 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, andmake). 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) orlibpcap(packet capture); or runtimes such as Python for a Python script. ldd $(which passwd)shows the libraries a command uses (libc.so.6,libpamfor pluggable authentication,libaudit,libselinuxon 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 -ivhcomplains 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.
| Command | Use |
|---|---|
dnf search zsh | search |
sudo dnf install [-y] zsh | install (-y skips confirmation) |
dnf list selinux* | list installed and available packages; dnf list installed for installed only |
sudo dnf update | update (consider scheduling) |
dnf groups list, sudo dnf groups install "Container Management" | package groups; quote names with spaces |
dnf provides */selinux | which package contains a file |
dnf history | review and undo transactions |
dnf repolist | enabled repositories |
15.7 apt (Ubuntu)
- apt replaces apt-get / apt-cache in daily use. Repositories:
/etc/apt/sources.listplus 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.
| Command | Use |
|---|---|
sudo apt update | refresh the package index first |
apt list --upgradable, sudo apt upgrade | see / install updates |
apt-cache search iotop | search packages |
sudo apt install iotop | install; services are started and enabled automatically on Ubuntu |
sudo apt autoremove | remove 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 listshows both installed and available packages. Usednf list installed | grep ftp(orrpm -qa | grep vsftpd) to check what's really installed.- Install via the software manager:
sudo dnf install -y vsftpd(nmap was already installed earlier).
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:
| Option | Purpose |
|---|---|
Port | listening port (e.g. 2022) |
PermitRootLogin | consider disabling direct root login |
AllowUsers | restrict who may log in |
PasswordAuthentication | allow/disallow passwords (create keys first!) |
Running on a non-default port (Red Hat family):
- SELinux must allow the port before starting:
sudo semanage port -a -t ssh_port_t -p tcp 2022(checkman semanage-portif the options error out). - Edit
Port 2022in/etc/ssh/sshd_config, thensudo systemctl restart sshd(config of the service changed β restart). - Verify:
ss -tulnshows 2022; testssh -p 2022 localhost. - Firewall (firewalld):
sudo firewall-cmd --add-port=2022/tcp --permanent, thensudo firewall-cmd --reload; checksudo 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_hostson 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(orssh-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
- Install, enable and start the SSH server; test access from another system (a second VM, or
localhost). - On the client machine (check which host you're on!) run
ssh-keygen(with or without a passphrase), thenssh-copy-id -p 2022 user@host(the-pmust be before the host). - Log in again: with a passphrase GNOME offers to cache it for the session.
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
| Tool | Use |
|---|---|
date | show time; formatting: date +%d-%m-%Y (%Y four-digit year, %y two-digit; see man date). Can set time, but not the best tool |
hwclock | hardware clock; --systohc (system β hardware), --hctosys (hardware β system) |
timedatectl | the 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(apoolline of Internet servers; add your own withserver NAME). Restart after changes. Check withchronyc 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 withtimedatectl; 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 statusshould 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.
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
| Action | How |
|---|---|
| Start in background | command & |
| Suspend a foreground job | Ctrl+Z |
| Resume suspended job in background | bg (or bg 1) |
| Bring job to foreground | fg 1 |
| List jobs of this shell | jobs |
| Interrupt foreground job | Ctrl+C |
sleep 3600 &
sleep 600 &
jobs
fg 1 # then Ctrl+Z, bg or Ctrl+C
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
| Command | Meaning |
|---|---|
ps aux | all processes, detailed (BSD style; also works as ps -aux) |
ps -ef | System V style full listing |
ps fax | process forest: parent/child relations |
ps aux --sort=-%mem / --sort pmem | sort by memory (ascending = biggest at bottom) |
ps -eo pid,args --forest | custom columns |
ps -L / -o ... nlwp | threads |
ps aux | grep sshdalso 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,cutto 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
18.7 Managing processes with kill
kill PIDsends a signal by PID;killall nameby 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
Lesson 19Scheduling Tasks
Goal: choose between cron, systemd timers and at, and schedule recurring and one-time tasks.
19.1 Options overview
| Tool | Use |
|---|---|
| cron | classic recurring tasks; crond/cron daemon, edit with crontab -e |
| at | run a task once in the future; needs atd running |
| systemd timer | modern 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/crontabis 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 lyndaedits a crontab for a specific user (-eedit,-uuser). Without sudo it edits your own;crontab -llists.
* * * * * 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.
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=trueremembers missed runs;RandomizedDelaySecspreads 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
/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
- File in 5 minutes:
echo "touch /tmp/testfile" | at now + 5 minutes - Run fstrim daily:
systemctl cat fstrim.timer(weekly by default) βsudo systemctl edit fstrim.timerand add
Verify with[Timer] OnCalendar=dailysystemctl status fstrim.timer(shows next trigger). Seeman systemd.timefor time specs. - Hello to syslog at 16:00:
crontab -eβ0 16 * * * logger hello
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).
| Command | Shows |
|---|---|
journalctl | the whole journal (~70,000 lines in demo) |
journalctl -u sshd.service | one unit (tab completion lists them all) |
journalctl -k / dmesg | kernel messages only, for kernel-related troubleshooting |
journalctl -u crond --since yesterday --until now | time range filter |
journalctl -p info | priority info and above (lots) |
journalctl -p err | errors only: most useful when troubleshooting |
journalctl -xb | b = current boot, x = explanations (extra help lines for common failures) |
/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 fileauthpriv.* /var/log/secure: authentication
- Log files are plain text: read with
sudo less /var/log/messages(G = bottom),tail -fto 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.
/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)
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
dockerwithpodman(oralias docker=podman). - Red Hat family: Podman is available by default; Docker is not supported. Ubuntu:
sudo apt install docker.ioorsudo apt install podman. - Registries: Docker Hub (hub.docker.com) is the biggest, useful for Podman users too (usage docs for each image).
docker login REGISTRYif 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
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.
| Need | Option |
|---|---|
| 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
~/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
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
- GRUB (Grand Unified Bootloader): has a shell, useful to influence boot.
- Kernel loaded together with initrd/initramfs (essential drivers).
- systemd: early boot (essential system components), then services, then a shell/login.
From the GRUB menu add kernel parameters for troubleshooting:
| Parameter | Effect |
|---|---|
systemd.unit=emergency.target | jumps in right before early boot: minimum services, hardcore troubleshooting |
systemd.unit=rescue.target | after early boot: more of the normal system available, easier to fix |
systemd.unit=multi-user.target | complete operational environment (no GUI) |
systemd.unit=graphical.target | normal 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
linuxloads the kernel (vmlinuz). Append parameters (removerhgb quiet/quiet splashto see boot messages). Ctrl+X boots. - Boot arguments are not persistent; used for troubleshooting.
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.
| Command | Use |
|---|---|
lsmod | loaded kernel modules |
lspci -k | PCI devices with the kernel module in use (e.g. Ethernet controller β e1000e; VGA β vmwgfx) |
lsusb | USB bus and devices |
modprobe NAME | load a module manually (rarely needed) |
modprobe -r NAME | remove 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
22.6 Command review
systemd-udevd, modprobe, lsmod, lspci, lsusb.
Lab: boot parameters (emergency vs rescue)
- Reboot, edit GRUB entry (e), remove
rhgb quiet, addsystemd.unit=emergency.target, boot with Ctrl+X, enter the root password. systemctl list-unitsshows ~98 units, mostly devices and only essential services.systemctl start rescue.targetto move on: more units (mounts, more services).rebootto return to normal mode. (Rescue shows fewer units in some respects because emergency addresses devices differently, aiming to give access to all hardware.)
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 monitortraces events live when you plug/unplug a device (e.g. a USB drive: device initialised as sda/sda1,exfatmodule 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
| Command | Lists |
|---|---|
sudo lshw | less | everything (very detailed; run as root; use specific tools for specific needs) |
lscpu | CPU details (merges /proc/cpuinfo with more): model, cores, cache |
lsblk | block devices (disks, removable media) |
lspci / lspci -k | PCI devices / with kernel modules used |
lsusb | USB devices |
lsmem | memory configuration; interesting with NUMA (non-uniform memory access) topology |
lsinitrd | contents of the initrd image (directory structure and drivers), to check whether a driver is included |
23.3 Hardware properties
- Properties live in
/sys, but it's complicated; useudevadm info:sudo udevadm info /dev/cdromshows all properties (and the underlying /sys/devices path). modinfo MODULEshows 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).
lspci -kshows the 3D controller using the nouveau driver. AI work needs CUDA, which nouveau doesn't provide.- Enable RPM Fusion (free + non-free repos; accept the GPG key).
dnf install akmod-nvidia xorg-x11-drv-nvidia-cuda(~0.5 GB; includes CUDA). On modern Fedoraakmods --forceis not needed.dracut --forceto rebuild the initramfs so the new driver is available at boot, thenreboot.- Verify:
lspci -kshows nvidia, nvidia_drm;nvidia-smishows the GPU. Bonus:dnf install nvtopfor GPU activity.
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
--permanentto survive reboot, then--reloadto 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_tmay access files labelledhttpd_sys_content_t(document root/var/www/html). - Denials go to the audit log:
sudo grep AVC /var/log/audit/audit.log. Also checksealertmessages in the logs (sudo grep sealert /var/log/messages), which suggest fixes. Read the explanation, it's sometimes good, sometimes not.
| Command | Use |
|---|---|
getenforce | show mode (Enforcing / Permissive / Disabled) |
setenforce 0|1 | Permissive/Enforcing, temporary (until reboot), to test whether SELinux is the problem |
ps auxZ, ls -Z, ls -dZ /web | show contexts (the t part, the type, matters) |
semanage fcontext -a -t TYPE 'PATH(/.*)?' | define a file context in the policy |
restorecon -Rv PATH | apply the policy context to the file system |
semanage port -a -t http_port_t -p tcp 82 | allow a service to bind a non-standard port |
Demo: Apache with a custom document root
- Edit
/etc/httpd/conf/httpd.conf:DocumentRoot "/web"and the matching<Directory>block. mkdir /web;echo hello | sudo tee /web/index.html;systemctl restart httpd;curl localhoststill shows the default page.ls -dZ /webβdefault_t. The policy allows httpd_t β httpd_sys_content_t, not default_t (that would open Apache to everything).- AVC denial in audit log confirms it (source httpd_t, target default_t).
- 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
(/.*)? 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-statusshows 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.
| Command | Use |
|---|---|
apparmor_parser -a FILE / -r FILE | load / reload (replace) a profile |
aa-genprof PROGRAM | generate a profile (package apparmor-utils) |
aa-complain PROFILE | logging-only mode, for tuning |
aa-enforce PROFILE | back to enforcing |
Demo: profile for vim
sudo apt install apparmor-utils;sudo aa-genprof vim- In another terminal use the program as fully as possible (demo:
vim /etc/motd, edit, save). - 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.
sudo aa-status | grep -C5 vimshows the new profile. Now writing to a file in /root fails with "can't open file for writing": the profile is doing its job.- 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
firewall-cmd --add-service=http --permanent. On Ubuntu: package apache2, ufw allow 80/tcp, and AppArmor needs no extra port step.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).
No lesson matches that search.