SYNTHESIZED FROM STAR V LEARNING CENTERS COURSE MATERIALS · JACKSONVILLE, FL
| Distribution Family | Package Manager | Package Format | Common Distros |
|---|---|---|---|
| Red Hat (RPM-based) | RPM / YUM / DNF | .rpm | RHEL, Fedora, CentOS, Rocky Linux, AlmaLinux |
| Debian-based | dpkg / APT | .deb | Debian, Ubuntu, Linux Mint, Kali Linux |
| SUSE-based | Zypper / RPM | .rpm | openSUSE, SUSE Linux Enterprise |
The FHS defines where different types of files live on every Linux system. Know all of these — they appear in exam questions constantly.
history command shows recent commands. Saved in ~/.bash_history after session ends.
Bash Command Structure
ls -l /etc — list command, long format option, /etc argument.
command subcommand argumentExample: ip addr show eth0 — ip command, addr subcommand, show sub-subcommand.
Case sensitiveLinux is case-sensitive. File.txt and file.txt are different files.
Space sensitiveSpaces separate command arguments. Use quotes for filenames with spaces: cat "my file.txt".
apropos topic. Finds relevant commands when you don't know the exact name.
/usr/share/docExtended documentation for installed packages. README files, changelogs, examples.
Key /boot Directory Files
initrd Management
dracut --force regenerates the initramfs for the current kernel. Required after adding storage drivers or making hardware changes that affect early boot.
mkinitrdLegacy tool for generating initrd images. Still referenced in some environments and the XK0-006 objectives. On modern systems, dracut has replaced it.
grub2-install [options] /dev/sda
grub2-mkconfigBuilds grub.cfg from source files. Always run after modifying /etc/default/grub. grub2-mkconfig -o /boot/grub/grub.cfg. Some distros use update-grub as a shortcut.
/etc/default/grubAdmin-editable GRUB2 settings file. Modify here, then run grub2-mkconfig. Controls timeout, default OS, kernel parameters.
Boot Targetssystemctl get-default — view current default target. systemctl set-default graphical.target — set GUI boot. systemctl set-default multi-user.target — set CLI boot.
Partition Table Types
Common Filesystem Types
usermod -aG wheel username. On Debian/Ubuntu the equivalent group is called sudo.
sudo groupOn Debian/Ubuntu: members of the sudo group are allowed to use sudo. Equivalent to wheel on RHEL. usermod -aG sudo username.
-c comment, -e expiry, -s shell, -m create home dir, -G supplementary groups.
adduser usernameHigher-level interactive user creation command (Debian/Ubuntu). More user-friendly than useradd — prompts for password and info. Creates home directory by default.
usermod options userModify existing user. -L lock, -U unlock, -aG group add to group (append), -s /bin/bash change shell.
userdel usernameDelete user account. -r also removes home directory and mail spool.
deluser usernameHigher-level user deletion (Debian/Ubuntu). Equivalent to userdel. deluser --remove-home username also removes home directory.
passwd usernameSet or change a user's password. -l lock. -u unlock. -d delete password (passwordless).
chage options userModify password aging. -l list, -M 90 max 90 days, -m 7 min 7 days, -W 14 warn 14 days, -E 2025-12-31 expiry.
chsh -s /bin/zshChange user's login shell.
getent passwd usernameQuery the Name Service Switch databases — works for local accounts AND LDAP/AD-joined systems. More reliable than reading /etc/passwd directly in enterprise environments.
id usernameDisplay UID, GID, and all group memberships. Also shows EUID and EGID.
groups usernameList all groups a user belongs to.
whoamiDisplay current username.
whoDisplay currently logged-in users with terminal, login time, and source IP.
lastlogMost recent login for all users.
lastLogin history from /var/log/wtmp.
wCurrently logged-in users and their activity including idle time and current process.
-n newname rename. -g GID change GID.
groupdel groupnameDelete a group. Cannot delete a group that is a user's primary group.
usermod -aG sales userAdd user to supplementary group. The -a flag is critical — without it, the user is removed from all other supplementary groups.
visudo).
su - rootSwitch User. Switches to root with root's full environment (- flag). Requires knowing root's password. Gives full root shell — riskier and less auditable than sudo.
visudoSafe editor for /etc/sudoers. Validates syntax before saving — prevents lockout from syntax errors. Never edit /etc/sudoers directly.
/etc/sudoersDefines who can use sudo and what commands. Format: username ALL=(ALL:ALL) ALL gives full sudo access. NOPASSWD: allows passwordless sudo for specific commands.
PolicyKit / pkexecGraphical privilege delegation. More granular than sudo. Controls actions like device mounting, network configuration, shutdown. Policy files define which actions are permitted without root password.
/etc/ssh/sshd_config
Relative PathPath relative to your current working directory. Does NOT start with /. Example: if pwd is /etc, then ssh/sshd_config is the relative path to the same file.
. (single dot)Represents the current directory. ./script.sh = run script in current directory.
.. (two dots)Represents the parent directory — one level up. cd .. moves up one level.
~ (tilde)Represents the current user's home directory. cd ~ = go home. ~/projects = projects folder in home dir.
- (dash)Previous directory. cd - switches back to where you just were. Useful for toggling between two directories.
-a shows hidden (dot) files. -d shows directories only.
cd ~Change to home directory. cd / = root. cd .. = up one level. cd - = previous directory.
pwdPrint Working Directory. Shows absolute path to your current location.
treeDisplays the filesystem in a hierarchical tree-like format. tree /etc shows the /etc structure visually.
touch fileCreate an empty file, or update the timestamp of an existing file without modifying its contents.
mkdir -p a/b/cCreate directory. -p creates parent directories as needed.
rmdir dirRemove an EMPTY directory. Fails if directory contains files. Use rm -rf dir/ for non-empty directories.
cp -r src/ dst/Copy files or directories. -r = recursive (required for directories).
mv src dstMove or rename files/directories.
rm -rf dir/Delete files. -r = recursive. -f = force (no prompts). No Recycle Bin — permanent deletion.
cat fileDisplay entire file contents. Concatenate files: cat file1 file2. Create files: cat > newfile.
less fileDisplay file one page at a time. Scroll up AND down. Search: /keyword. Quit: q. Preferred over more.
more fileDisplay file one page at a time. Older — forward scroll only. Space = next page. q = quit.
head -n 20 fileDisplay first 20 lines. Default is 10. Good for viewing notes at top of config files.
tail -f /var/log/syslogDisplay last lines. -f = follow (real-time monitoring). Best for watching live logs.
grep -i "pattern" fileSearch for patterns. -r = recursive. -i = case-insensitive. -n = show line numbers.
find /etc -name "*.conf"Search for files. -name by filename, -type f/d file/dir, -perm 755 by permissions.
locate filenameFast file search via pre-built index (/var/lib/mlocate/mlocate.db). Much faster than find but may be stale.
updatedbRebuild the locate index. Run as root to ensure locate results are current.
which commandShows the full path of a command found in $PATH. Confirms which version will run.
stat fileDetailed file metadata: size, inode number, permissions, ownership, access/modify/change timestamps, storage blocks.
file filenameIdentify file type from content, not extension. Useful when extension is missing or misleading.
wc -l fileCount lines (-l), words (-w), or bytes (-c).
sort fileSort lines alphabetically. -n = numeric. -r = reverse.
uniq fileRemove duplicate adjacent lines. Usually piped after sort.
cut -d: -f1 /etc/passwdExtract fields. -d = delimiter, -f = field number.
awk '{print $1}' filePattern scanning and processing. More powerful than cut.
sed 's/old/new/g' fileStream editor. Search/replace, delete lines. -i = in-place edit.
df -hShow disk free space in human-readable format.
du -sh /var/logShow disk usage of a directory.
ln file hardlink
Symbolic Link (Symlink)Points to another filename, not data. Has its own unique inode. Can cross filesystem boundaries and link to directories. Becomes dangling (broken) if target is deleted. Create: ln -s target linkname
ls -li — hard links show identical inode numbers. Data deleted only when hard link count reaches zero. Symlinks break when target is removed.!! repeats last command. !ssh repeats last ssh command.
ls | tee output.txt
xargsBuild command lines from stdin. find . -name "*.log" | xargs rm
Every file has a 10-character permission string: -rwxr-xr--
Type: - = file · d = directory · l = symlink · b = block device · c = character device
| Permission | Symbol | Octal | On Files | On Directories |
|---|---|---|---|---|
| Read | r | 4 | View file contents | List directory contents (needs execute too) |
| Write | w | 2 | Edit/modify file | Create, rename, delete files (needs execute too) |
| Execute | x | 1 | Run as program/script | Enter directory and access contents |
| None | - | 0 | No permission | No permission |
chmod / chown
-R for recursive.
Special Permissions
chattr / lsattr / ACLs
Vim — Three Modes
i. Edits file content. a = after cursor, o = new line below, I = start of line, A = end of line.
Execute ModePress :. File commands: :w save, :q quit, :wq save and quit, :q! quit without saving, :w newname save as.
Vim Command Mode Keys
nano — No Modes
Gedit
GUI-based text editor. Pull-down menus. Requires graphical environment. Not available on headless servers.
-c create, -x extract, -t list, -v verbose, -f filename, -r append.
tar -czvf archive.tar.gz dir/Create gzip-compressed archive. -z = gzip. Most common for backups.
tar -xzvf archive.tar.gzExtract gzip-compressed archive.
tar -cjvf archive.tar.bz2 dir/Create bzip2-compressed archive. -j = bzip2. Better compression, slower.
gzip / gunzipCompress/decompress .gz files. Fast, good compression ratio.
bzip2 / bunzip2Compress/decompress .bz2 files. Better compression than gzip, slower.
xz / unxzCompress/decompress .xz files. Best compression, slowest. Used for large source packages.
zip / unzipWindows-compatible archive format. Cross-platform transfers.
cpioCopy In/Out. Directory tree backup. -o = backup, -i = restore, -v = verbose.
ddLow-level data copy. Disk images, drive cloning, secure wiping, bootable USB. dd if=/dev/sda of=disk.img. if= input, of= output. No confirmation — use with care.
rsyncRemote sync. Only transfers changed data (delta). rsync -avz src/ user@host:/dst/. SSH-encrypted. Best tool for ongoing incremental backups.
| Tool | Era | Key Commands | Notes |
|---|---|---|---|
| rpm | Legacy | rpm -ivh pkg.rpm install · rpm -e pkg remove · rpm -qa list all · rpm -qi pkg info | Low-level. No dependency resolution. Manual dependency management. |
| yum | Older | yum install pkg · yum remove pkg · yum update · yum list installed | Wraps rpm. Handles dependencies automatically. Being replaced by dnf. |
| dnf | Current | dnf install pkg · dnf remove pkg · dnf upgrade · dnf info pkg | Default for Fedora, RHEL 8+. Faster than yum. Better dependency handling. |
RPM Repository Configuration
| Tool | Key Commands | Notes |
|---|---|---|
| dpkg | dpkg -i pkg.deb install · dpkg -r pkg remove · dpkg -l list · dpkg -s pkg status | Low-level. No dependency resolution. |
| apt | apt update refresh lists · apt upgrade update packages · apt install pkg · apt remove pkg · apt show pkg | Two-step update: apt update first (refreshes index), then apt upgrade (installs updates). |
APT Repository Configuration
zypper install pkg, zypper remove pkg, zypper update. Uses RPM packages. Know this exists for the exam — SUSE is a distinct family.
pip install package. Uses virtual environments to isolate dependencies (python3 -m venv env).
cargo (Rust)Rust package manager. Handles builds and dependencies. cargo install package.
npm (Node.js)Node Package Manager for JavaScript. npm install package. -g flag for global installation.
tar -xf sourcecode.tar.gzcd sourcecode/./configure — checks dependencies and creates Makefilemake — executes instructions in Makefile, compiles codemake install — copies binaries to system directorieswget https://example.com/file.tar.gz.
curlTransfers data using many protocols (HTTP, HTTPS, FTP, SFTP, SCP, LDAP, and more). Supports upload and sending. Used heavily in scripting and API testing. curl -O https://example.com/file.
SnapsCanonical's containerized package format. Self-contained — includes all dependencies. Auto-update. Runs in a sandbox. Cross-distribution.
FlatpakUniversal packaging system. Cross-distribution. Sandboxed. Pulls from "remotes" (repositories). Per-system or per-user installation. More isolation than traditional packages.
AppImagePortable — runs without installation. Mounted as a drive. No root required. Limited sandboxing compared to Snaps and Flatpak.
p print, n new, d delete, w write (save). Use gdisk for GPT disks.
gdisk /dev/sdbGPT-aware version of fdisk. Use for disks over 2TB or when GPT is required.
parted /dev/sdbMore powerful partition manager. Supports both MBR and GPT. Can resize partitions.
partprobeInform the OS kernel of partition table changes without rebooting. Run after modifying partition tables with fdisk/parted.
lsblkList block devices in tree format. Shows device name, size, type, and mount point. Most useful first step for storage troubleshooting.
blkidDisplay block device attributes including UUID, filesystem type, and label. UUIDs used in /etc/fstab for reliable mounting.
growpart /dev/sda 1Grow a partition to fill available space after resizing a virtual disk.
mkfs.xfs, mkfs.btrfs for other formats.
fsck /dev/sda1Check and repair filesystem. Only run on unmounted filesystems. Can repair ext4 superblock corruption. Use xfs_repair for XFS.
e2label /dev/sdb1 dataAssign a label to ext4 filesystem.
resize2fs /dev/sdb1Resize ext4 filesystem after growing the partition. Grow: resize2fs /dev/sdb1. Shrink: resize2fs /dev/sdb1 10G.
tune2fs /dev/sdb1Adjust ext4 filesystem parameters — reserved blocks, mount count, check interval.
dumpe2fs /dev/sdb1Display ext4 superblock and block group information.
xfs_repair /dev/sdb1Repair corrupt XFS filesystem. Must be unmounted.
xfs_growfs /mountpointExpand XFS filesystem to fill available space. XFS can grow but NOT shrink — plan carefully.
umount not "unmount." Cannot unmount if files are open.
/etc/fstabFilesystem table. Defines filesystems to mount automatically at boot. Six fields: device (UUID preferred), mount point, filesystem type, options, dump, pass.
/etc/mtabCurrently mounted filesystems. Updated dynamically by the kernel.
/proc/mountsKernel's view of current mounts. More reliable than /etc/mtab.
autofsAuto-mount daemon. Mounts filesystems on demand when accessed and unmounts after idle period. Efficient for NFS and network shares.
Common Mount Options (in /etc/fstab)
Network Mounts
mount server:/share /mnt.
SMB / Samba (CIFS)Windows-compatible file sharing. Samba implements SMB on Linux. Mount: mount -t cifs //server/share /mnt. Used in mixed Windows/Linux environments.
LVM is a flexible storage management layer that combines multiple physical disks into logical volumes that can span multiple disks and be resized without downtime.
LVM Layers (bottom to top)
pvcreate /dev/sdbvgcreate vg_data /dev/sdb /dev/sdclvcreate --name lv_data --size 500G vg_datamkfs.ext4 /dev/vg_data/lv_dataLVM Commands Reference
Physical Volumes
Volume Groups
Logical Volumes
cat /proc/mdstat shows current RAID status.
/proc/mdstatKernel's view of current software RAID status. Check here first when troubleshooting RAID issues.
LUKSLinux Unified Key Setup. Standard for full-disk encryption on Linux. Managed with the cryptsetup command. Encrypts data at rest. Transparent to applications once unlocked.
cryptsetupTool for managing LUKS-encrypted volumes. cryptsetup luksFormat /dev/sdb1 to encrypt. cryptsetup open /dev/sdb1 name to unlock.
usrquota and grpquota mount options. Soft limit = warning threshold. Hard limit = absolute maximum. Grace period between soft and hard limits.
iostatReports CPU and I/O statistics. Transfers per second, blocks read/written. Use to identify storage bottlenecks.
iopingReports I/O latency for storage devices. Measures IOPS performance.
fioFlexible I/O tester. Benchmarks storage performance under various workload patterns.
command 2>/dev/null suppresses error output.
/dev/zeroSource of null bytes. Used to create files filled with zeros. dd if=/dev/zero of=file bs=1M count=100 creates a 100MB file of zeros.
/dev/urandomCryptographically secure pseudo-random number generator. Source of random data for key generation, secure wiping. Non-blocking.
udevDevice manager for the Linux kernel. Automatically creates device files in /dev when hardware is detected. Manages device naming and permissions.
-v for verbose detail.
lsusbList USB devices and attributes.
lshwComprehensive hardware lister. More detail than lspci/lsusb. Covers all hardware classes. -short for summary.
hwinfoDetailed hardware info. Flags: --cpu, --storage, --usb, --netcard.
dmidecodeReads DMI/SMBIOS data from firmware. System model, serial number, BIOS version, memory details.
dmesgKernel ring buffer messages from boot. Hardware detection, driver errors, disk errors. dmesg | grep error to filter.
ipmitoolIntelligent Platform Management Interface tool. Manages server hardware out-of-band. Monitor sensors, power cycle remotely, read system event logs, manage fans and power without OS. Used with IPMI/BMC on servers.
lm_sensors / sensorsLinux monitoring sensors. Reads hardware temperature, voltage, fan speed from motherboard sensors. Run sensors-detect first to configure, then sensors to view readings. Essential for thermal monitoring.
nvtopGPU process monitor. Like top but for GPUs. Shows GPU utilization, memory usage, temperature, and running processes. Used for GPU workload monitoring (AI/ML, rendering).
cat /proc/cpuinfoCPU info dynamically from kernel. Cores, stepping, cache, flags.
cat /proc/meminfoMemory info: total, free, available, cached, swap.
cat /proc/<PID>/Per-process virtual filesystem. /proc/PID/status (process info), /proc/PID/fd (open file descriptors), /proc/PID/maps (memory mappings). Useful for deep process inspection.
-e all, -f full format, -p PID specific process.
topDynamic real-time process monitor. Upper: system summary. Lower: process list sorted by CPU. Interactive: k kill, r renice, q quit.
htopEnhanced top. Color-coded, scrollable, tree view. F6 sort, F9 kill.
atopAdvanced system and process monitor. Records all activity at configurable intervals for historical analysis. Shows CPU, memory, disk, and network per process. Useful for post-incident analysis of what was happening at a specific time.
mpstatMulti-processor statistics. Shows CPU utilization per core. mpstat -P ALL shows all CPUs. Useful for identifying CPU imbalance across cores.
pidstatPer-process statistics including CPU, memory, I/O, and context switching. pidstat -u CPU, -r memory, -d disk I/O. More detailed than ps for resource tracking.
straceTraces system calls and signals for a process. Tells you exactly what a program is asking the kernel to do. Powerful debugging tool: strace -p PID attaches to running process. strace command traces from start. High overhead — use carefully in production.
pgrep sshFind PID of processes by name.
pidof sshdFind PID of a running program.
kill -9 PIDSend signal. -9 SIGKILL (force, no cleanup). -15 SIGTERM (graceful, default). -1 SIGHUP (reload config). -2 SIGINT (same as Ctrl+C).
killall sshdKill all processes matching the name.
pkill -u usernameKill processes by name pattern or user. pkill -u username kills all processes owned by that user. More flexible than killall.
nohup command &Run a command that continues after logout. "No Hang Up" — immune to SIGHUP signal. Output redirected to nohup.out by default. Use when you need a long-running job to survive a disconnected SSH session.
pstreeDisplay processes in tree showing parent/child relationships.
lsofList Open Files. Shows which files/sockets each process has open. lsof -u username, lsof /dev/sda1.
sarSystem Activity Reporter. Collects CPU, memory, I/O, network statistics for performance analysis.
uptimeUptime, logged-in users, and load averages for 1, 5, and 15 minutes.
-h = human-readable. High available memory = healthy. Low available = potential performance issues.
vmstatVirtual memory statistics. Shows swapping activity, I/O, CPU. High swap usage = system needs more RAM.
mkswap /dev/sdb2Initialize a partition as swap space.
swapon /dev/sdb2Activate swap space. Add to /etc/fstab for persistence.
swapoff /dev/sdb2Deactivate swap space.
-r to unload.
depmodRebuild module dependency database. Run after adding new modules.
sysctl -aDisplay all kernel parameters. sysctl -w parameter=value to change. sysctl -p to load from /etc/sysctl.conf.
uname -rDisplay kernel version (release). uname -a shows all information including architecture and hostname.
| Feature | systemd | SysVinit |
|---|---|---|
| Init system | Current standard (PID 1) | Legacy, largely replaced |
| Boot speed | Parallel service startup | Sequential — slower |
| Configuration | Unit files (.service, .target) | Init scripts in /etc/init.d/ |
| Runlevels | Targets (graphical.target, multi-user.target) | Runlevels 0–6 |
| Main tool | systemctl | service, chkconfig |
| Logging | journald (binary) | rsyslog (text) |
SysVinit Runlevels (legacy reference)
systemctl set-default multi-user.target = boot to CLI.
systemctl list-unitsList all active units and their status.
Additional systemd Utilities
systemd-analyze blame shows time each service took to start — same as systemd-blame. systemd-analyze critical-chain shows the slowest chain of services.
systemd-blameSame as systemd-analyze blame — lists all services sorted by startup time. Used to identify slow-starting services that delay boot.
timedatectlDisplay and set system time, date, timezone, and NTP sync status. timedatectl set-timezone America/New_York. timedatectl set-ntp true enables automatic NTP sync.
resolvectlQuery systemd-resolved for DNS information. resolvectl query example.com resolves a hostname. resolvectl status shows current DNS configuration per interface.
hostnamectlDisplay and set system hostname. hostnamectl set-hostname server01. Persists after reboot.
daemon-reloadsystemctl daemon-reload — reload systemd manager configuration. Required after creating or modifying unit files. Does NOT restart services — just makes systemd aware of the changed configuration.
systemctl edit serviceOpen a drop-in override file for a service unit. Edit without modifying the original package-provided unit file. Changes survive package updates.
systemctl unmask serviceRemove a mask (the strongest disable) from a service, allowing it to be started again.
OnCalendar=daily for daily execution. Paired with a matching .service unit.
.mountManages mount points. Automatically mounts filesystems. Generated from /etc/fstab entries.
.socketSocket-based activation. Service only starts when a connection comes in on the defined socket. Efficient for infrequently used services.
journalctl. Faster searching than text files.
journalctl -u sshdView logs for a specific service. -f = follow. -n 50 = last 50 lines. --since "1 hour ago" = time-filtered.
Syslog Severity Levels (0–7, 0 = most critical)
| Level | Name | Meaning |
|---|---|---|
| 0 | emerg | System is unusable. Broadcast to all users. |
| 1 | alert | Immediate action required. |
| 2 | crit | Critical conditions. Hardware failures. |
| 3 | err | Error conditions. |
| 4 | warning | Warning — may indicate future error. |
| 5 | notice | Normal but significant condition. |
| 6 | info | Informational messages. |
| 7 | debug | Debug-level messages. Very verbose. |
Key Log File Locations
crontab -e. Five-field format: minute hour day month weekday command. * = any. Example: 0 2 * * * /scripts/backup.sh runs at 2am daily. Requires system to be running at the scheduled time.
crontab -lList current user's cron jobs.
anacronRuns jobs that were missed if the system was powered off or asleep. Unlike cron, it does not require the system to be running at a specific time — it runs jobs after the system comes back up if the job was missed. Configured in /etc/anacrontab. Used for daily/weekly/monthly maintenance tasks on systems that aren't always on.
atSchedule one-time tasks. Interactive: at 4pm then enter commands, Ctrl+D to finish. Non-interactive: echo "command" | at 4pm.
Crontab Field Format
| Service | Config File | Port | Notes |
|---|---|---|---|
| SSH (sshd) | /etc/ssh/sshd_config | 22/TCP | Disable root login, use key-based auth. Restart required after config changes. |
| NTP (ntpd/chrony) | /etc/ntp.conf or /etc/chrony.conf | 123/UDP | Time synchronization. chrony better for intermittently connected systems. |
| NFS | /etc/exports | 2049/TCP+UDP + 111 | showmount -e [IP] to list exports. Clients mount with standard mount command. |
| Apache (httpd) | /etc/httpd/conf/httpd.conf | 80/TCP (443 HTTPS) | DocumentRoot = /var/www/html. systemctl start httpd. |
| CUPS (printing) | /etc/cups/cupsd.conf | 631/TCP | Web-based admin at http://localhost:631. lpr = print. lpq = queue. |
| rsyslog | /etc/rsyslog.conf | 514/UDP | Log forwarding. Remote logging for centralized SIEM. |
ip addr (show IPs), ip link (show interfaces), ip route (show routing table). Changes are temporary unless added to config files.
ifconfig (legacy)Older network configuration. Still found on many systems. Being replaced by ip. ifconfig eth0 shows interface details.
NetworkManagerNetwork management service. Three interfaces: nmcli (CLI), nmtui (text UI — blue screen), nmgui (graphical). Default on most modern distributions.
nmcli commandsnmcli general status — overview. nmcli connection show — list connections. nmcli con up eth0 — activate. nmcli con down eth0 — deactivate. nmcli device status — device state.
nmtuiText-based NetworkManager UI. Blue screen interface. Edit connections, activate/deactivate, set hostname. No graphical environment required.
NetplanUbuntu's declarative network configuration tool. YAML-based. Files in /etc/netplan/. Apply changes: netplan apply. Test changes: netplan try (auto-reverts). Check status: netplan status.
ethtoolManage NIC driver settings. Check and configure speed, duplex, Wake-on-LAN, link status.
192.168.2.42 server01 server01.example.com
/etc/resolv.confDNS server configuration. nameserver 192.168.2.10 — specifies DNS server IP addresses.
/etc/nsswitch.confName Service Switch. Controls lookup order for hostname resolution, user info, groups. Example: hosts: files dns = check /etc/hosts first, then DNS.
/etc/sysconfig/network-scripts/Per-NIC configuration files on RHEL/CentOS/Fedora. ifcfg-eth0, etc.
hostnamectlDisplay and set system hostname. hostnamectl set-hostname server01. Persists after reboot.
ssh-keygen — creates private key (~/.ssh/id_rsa) and public key (~/.ssh/id_rsa.pub).ssh-copy-id user@192.168.2.200 — appends public key to server's ~/.ssh/authorized_keys.ssh user@192.168.2.200 — should authenticate without password using private key.SSH config file: /etc/ssh/sshd_config. Key options: Port (default 22), PermitRootLogin no, PasswordAuthentication no (force key-based only). Restart sshd after any config change.
ping -c 4 for exactly 4 packets.
tracerouteTrace packet path to destination showing each hop and RTT. Uses UDP by default on Linux (-I for ICMP).
tracepathSimilar to traceroute but doesn't require root privileges.
mtrMy Trace Route. Combines ping + traceroute in real-time. Shows packet loss and latency per hop. Best tool for diagnosing path-specific issues.
nslookup domainQuery DNS records. Basic tool for name resolution testing.
dig @server domainDNS query with more detail than nslookup. Can specify a specific DNS server. dig example.com MX for mail records.
host domainSimple DNS lookup. Quick and clean output.
whois domainDomain registration and ownership information.
resolvectl queryQuery name resolution via systemd-resolved. resolvectl query example.com
arp -aDisplay ARP cache — IP to MAC address mappings known to the local system.
netstat / ssShow active connections and listening ports. ss -tuln = TCP/UDP listening ports numeric. ss is the modern replacement for netstat.
nmapNetwork scanner. Discover hosts, open ports, OS, services. nmap -sn 192.168.2.0/24 host discovery only.
iftopReal-time bandwidth utilization per connection. Visual display of network traffic.
iperf3Test maximum network throughput between two hosts. Requires iperf running on both ends.
nc (netcat)Networking Swiss army knife. Test connectivity, transfer data, create listeners. nc -zv host port to test if port is open.
scp user@host:/src /dstSecure copy over SSH. Encrypted file transfer.
sftp user@hostInteractive secure FTP session over SSH.
rsync -avz src/ user@host:/dst/Efficient sync/backup — only transfers changed data.
| Tool | Type | Distribution | Notes |
|---|---|---|---|
| iptables | Legacy firewall core | All | Tables → Chains → Rules. Still widely used. Being replaced by nftables. |
| nftables | Modern firewall core | All | Replaces iptables. Unified IPv4/IPv6. Simplified syntax. Better performance. |
| firewalld | Management interface | RHEL/Fedora | Manages nftables/iptables with zones. firewall-cmd tool. |
| UFW | Management interface | Ubuntu/Debian | Uncomplicated Firewall. Simplified interface for nftables/iptables. |
--permanent to persist after reboot.
firewall-cmd --zone=public --remove-port=21/tcpBlock FTP port in public zone.
firewall-cmd --reloadApply permanent changes. Required after adding --permanent rules.
Zones define trust levels. Public zone = least trusted (internet-facing). Trusted zone = most trusted (fully trusted network). Assign NICs to appropriate zones.
tcpdump -i eth0 port 53 captures DNS on eth0. -w file.pcap saves to file for Wireshark analysis. Most common installed on Linux servers.
WiresharkGUI packet analyzer. Decodes protocols, filters by many criteria. Opens .pcap files from tcpdump. Gold standard for deep packet analysis.
Nmap / ZenmapNetwork scanner. Host discovery, port scanning, OS fingerprinting, service version detection. Zenmap = GUI for nmap.
netstat / ssShow listening ports and active connections. ss -tuln = TCP/UDP listening ports. lsof -i also shows active network sockets.
mtrReal-time path analysis combining ping and traceroute. Shows per-hop packet loss and latency over time.
PermitRootLogin no in /etc/ssh/sshd_config.PasswordAuthentication no).SELinux implements Mandatory Access Control (MAC) at the kernel level. Even root cannot override SELinux policy. Default on RHEL/CentOS/Fedora/Rocky.
SELinux States
SELinux Commands
-R recursive.
semanage fcontextPermanently manage file context mappings. semanage fcontext -a -t httpd_sys_content_t "/web(/.*)?" then run restorecon.
getsebool -aList all SELinux booleans and their current state.
setsebool -P bool on/offSet SELinux boolean. -P makes it persistent across reboots.
audit2allowAnalyze audit log denials and generate a custom SELinux policy module to allow the denied action. Used for policy development when SELinux is blocking a legitimate operation.
sealertAnalyzes SELinux audit messages and provides human-readable explanations with suggested fixes. Most useful troubleshooting tool for SELinux denials.
gpg --verify file.sig file verifies a signature. Package managers automatically verify GPG signatures on packages before installing.
Secure Boot (UEFI)UEFI firmware feature that verifies each bootloader and kernel module is digitally signed by a trusted key before loading. Prevents bootkits and unauthorized OS loading. Supported by all major Linux distributions via shim bootloader signed by Microsoft.
SSH TunnelingSSH can forward network connections securely. Local forwarding (ssh -L local_port:remote_host:remote_port) tunnels a local port through SSH to a remote destination. Remote forwarding (ssh -R) exposes a local port on the remote server.
AllowUsers / AllowGroupsSSH daemon config options restricting which users/groups can log in via SSH. Set in /etc/ssh/sshd_config. Whitelist approach — only listed users/groups can connect. More restrictive than DenyUsers/DenyGroups.
Disable X ForwardingX11Forwarding no in sshd_config prevents forwarding of graphical applications over SSH. Reduces attack surface on servers that don't need GUI forwarding.
Remove unnecessary SUIDFind all SUID binaries: find / -perm -4000 -type f. Review each — remove SUID from any that don't require it. SUID binaries are a common privilege escalation target.
Disable unused filesystemsPrevent loading of rarely-used or unnecessary filesystem modules (cramfs, freevxfs, jffs2, hfs, etc.) via /etc/modprobe.d/. Reduces attack surface.
systemctl enable auditd.
audit.rulesConfiguration file for auditd rules (/etc/audit/audit.rules or /etc/audit/rules.d/). Define what to audit: file access, system calls, user actions. Example: -w /etc/passwd -p wa -k user-modify watches /etc/passwd for writes.
auditctlReal-time management of audit rules. auditctl -l list rules. auditctl -w /etc/sudoers -p wa add watch.
ausearchSearch the audit log. ausearch -k user-modify finds events with that key. ausearch -ui UID by user ID.
Winbind / SambaWinbind allows Linux systems to authenticate against Windows Active Directory domains. Part of the Samba suite. Enables Linux systems to join AD domains and use AD user/group accounts. Alternative to SSSD for AD integration.
#!/bin/bash for Bash. #!/usr/bin/python3 for Python. NOT a comment despite starting with #.
Comments# character marks a comment. Ignored by the interpreter. Document purpose, parameters, and examples.
Execute PermissionScripts need execute permission: chmod +x script.sh. Run from current directory: ./script.sh. If in $PATH, run by name: script.sh.
Exit Codes0 = success. Any non-zero = failure. Check with echo $? immediately after command. exit 1 to terminate with failure code.
$VAR or ${VAR}.
echo $VARPrint variable value to screen.
export VARMake variable available to child processes (environment variable).
read VARNAMERead user input into a variable. Interactive scripts use this for prompts.
Common Environment Variables
echo $PATH to view.
$HOMECurrent user's home directory path.
$USERCurrent logged-in username.
$SHELLPath to current shell binary (/bin/bash).
$HOSTNAMESystem hostname.
$PS1Shell prompt format string. Customize the command prompt appearance.
$DISPLAYX display identifier. Used by GUI applications to know which display to use.
Shell Config Files (loaded at login/startup)
ls | tee output.txt
xargsBuild and execute command lines from stdin. find . -name "*.log" | xargs rm deletes all found log files.
Here Doc (<<)Feed multi-line input to a command. cat << EOF ... EOF. The delimiter (EOF) marks the end of the input block.
if / if-else / case
if [ condition ]; then # code if true else # code if false fi case $VAR in "value1") echo "one" ;; "value2") echo "two" ;; *) echo "default" ;; esac
Loops
# while: runs while true while [ condition ]; do # code done # until: runs until true until [ condition ]; do # code done # for: fixed iterations for i in 1 2 3; do echo $i done
Comparison Operators
printf "%-10s %5d\n" "item" 42 — supports field widths and types. Does NOT add newline automatically.
tr 'a-z' 'A-Z'Translate or delete characters. echo "hello" | tr 'a-z' 'A-Z' converts to uppercase. tr -d '\r' removes carriage returns (Windows to Unix conversion).
bcBasic calculator. Handles floating-point math in scripts (Bash cannot natively). echo "scale=2; 10/3" | bc outputs 3.33.
read VARRead user input into variable.
exec commandReplace current shell with the specified command. The current process is replaced.
source fileExecute file in current shell (variables and functions remain). Also written as . file.
alias ll='ls -la'Create command shortcut. Define in ~/.bashrc for persistence.
test / [ ]Evaluate conditions. Exit code 0 = true, 1 = false. test -f file or [ -f file ].
echo $?Display exit code of the most recently executed command.
sed 's/old/new/g'Stream editor. Search and replace. -i = in-place edit. Powerful for bulk text manipulation in scripts.
awk '{print $2}'Pattern scanning. Extract specific fields, perform calculations, conditional processing on text.
| Tool | Agent | Language | Type | Notes |
|---|---|---|---|---|
| Ansible | Agentless | YAML | Config mgmt / Orchestration | Uses SSH. Easiest to learn. Most widely adopted. Cross-platform. Playbooks = task lists. |
| Puppet | Agentless (also agent) | Puppet DSL (Ruby-like) | Config mgmt | Enterprise and open source. Uses modules. Declarative — defines desired state. |
| Chef | Agent-based | Ruby | Config mgmt | Workstation → Server → Nodes. Recipes and cookbooks. More complex setup. |
| SaltStack | Both | Python / YAML | Config mgmt | Agent (minion) or agentless. Fast — uses ZeroMQ message bus. |
| Terraform | Agentless | HCL (Terraform) | Infrastructure provisioning | Cloud-focused. Provisions VMs, networks, storage. Works with AWS, Azure, GCP, and more. |
| Feature | Virtual Machines | Containers |
|---|---|---|
| Isolation | Full OS isolation | Process-level isolation (shares host kernel) |
| OS | Full guest OS per VM | Shares host OS kernel — no guest OS |
| Size | GBs (full OS image) | MBs (app + dependencies only) |
| Startup time | Minutes | Seconds |
| Overhead | High (full OS per VM) | Low |
| Portability | Moderate | High — run anywhere Docker runs |
| Security | Stronger isolation | Weaker — kernel compromise = all containers affected |
| Persistence | Full persistent state | Stateless by default — data lost on stop |
podman run, podman ps work identically to docker equivalents.
containerdIndustry-standard container runtime. Manages the complete container lifecycle — image pull/push, storage, networking, execution. Used by Kubernetes and Docker. OCI-compliant.
runCLow-level OCI-compliant container runtime. The actual tool that creates and runs containers. Used by containerd and other higher-level runtimes. Implements the OCI runtime specification directly.
-d detached. -p 8080:80 port mapping (host:container). -v /host:/container volume mount. -e VAR=value environment variable. --name myapp name the container.
docker exec -it name bashExecute a command inside a running container. -it = interactive terminal. Useful for debugging inside containers.
docker logs nameRead container stdout/stderr logs. -f follow in real-time.
docker inspect nameDetailed JSON info about a container or image. Network settings, volumes, environment variables, configuration.
docker ps -aList all containers including stopped. docker ps alone shows only running.
docker stop / rm nameStop then remove a container. docker rm -f name force-removes a running container.
docker build -t name .Build image from Dockerfile in current directory.
docker system pruneRemove all stopped containers, unused networks, dangling images, and build cache. Frees disk space.
FROM ubuntu:22.04
RUNExecute a command during build. Used to install packages, create directories, etc. Each RUN creates a new image layer.
COPY / ADDCopy files from host into the image. ADD also supports URLs and auto-extracts archives. Prefer COPY for clarity.
CMDDefault command to run when container starts. Can be overridden at runtime. If ENTRYPOINT is set, CMD provides default arguments to it.
ENTRYPOINTFixed command that always runs when the container starts. Cannot be easily overridden (unlike CMD). Use for containers designed to run a single application.
USERSet the user for subsequent RUN, CMD, and ENTRYPOINT instructions. Best practice: create a non-root user and switch to it before CMD.
EXPOSEDocuments which port the container listens on. Informational — does NOT actually publish the port (use -p at runtime for that).
ENVSet environment variables in the image that persist into the running container.
Image LayersEach Dockerfile instruction creates an immutable layer. Layers are cached — unchanged layers are reused on rebuild. Order matters: put frequently-changed instructions (COPY source code) last to maximize cache hits.
Image TagsLabels for specific versions of an image. nginx:1.24 = specific version. nginx:latest = most recent. Always pin to specific tags in production — latest changes unpredictably.
-v /host/path:/container/path. Direct host filesystem access.
Named VolumeDocker-managed storage. docker volume create mydata then -v mydata:/container/path. Data persists independently of containers. Preferred for production.
SELinux Volume ContextOn SELinux systems, add :z (shared) or :Z (private) to volume mounts: -v /host:/container:Z. Required for SELinux to allow container access to host directories.
Overlay FilesystemDefault storage driver for containers. Layers read-only image layers under a writable container layer. Changes only written to the top writable layer — base image unchanged.
Privileged vs UnprivilegedUnprivileged (default): container has limited capabilities. Cannot access host devices or most kernel features. Privileged (--privileged): container gets nearly all host capabilities. Security risk — use only when absolutely necessary (e.g., running Docker inside Docker).
Container Network Types
virsh list --all show all VMs. virsh start/shutdown/suspend/resume vmname. virsh snapshot-create-as create snapshot.
virt-installCLI tool for creating new virtual machines.
virt-managerGNOME-based GUI for managing KVM/QEMU VMs. Visual equivalent of VMware Workstation.
VirtIOParavirtualized device framework. Instead of emulating real hardware, VirtIO provides an optimized virtual device interface the guest OS communicates with directly. Significantly faster than full emulation for storage (virtio-blk) and networking (virtio-net). Requires VirtIO drivers in the guest OS.
Paravirtualized DriversGuest OS has knowledge that it is virtualized and uses optimized drivers (like VirtIO) instead of emulated hardware drivers. Better performance than full emulation. Requires driver support in the guest.
Nested VirtualizationRunning a hypervisor inside a VM. Enables running VMs inside VMs. Used for testing hypervisors and running cloud development environments. Must be enabled at the host hypervisor level.
VM Network Types
VM Disk Image Operations
qemu-img convert -f vmdk -O qcow2 disk.vmdk disk.qcow2 converts VMware to QEMU format.
qemu-img resizeResize a disk image. qemu-img resize disk.qcow2 +20G adds 20GB. Then grow partition and filesystem inside the VM.
qemu-img infoDisplay image properties: format, virtual size, actual disk usage, snapshots.
-u unified format (used in patches). Essential for config management and troubleshooting configuration drift.
sdiff file1 file2Side-by-side diff. Displays both files in columns with differences highlighted. Easier to read than standard diff for manual comparison. -s only shows differing lines.
smartctl -a /dev/sda. Warning signs: reallocated sectors, pending sectors, uncorrectable errors. Backup immediately and replace drive.
Memory ErrorsSystem crashes, kernel panics. Test RAM with memtest86+. Check: recent hardware changes, heat, seating. Run memory dump analysis.
Zombie ProcessesProcess finished but parent hasn't released PID. Shows as Z in ps output. Kill the parent process to clean up. ps aux | grep Z
High CPUTop 5 CPU processes: ps aux --sort=-%cpu | head -6. Kill runaway processes. Check: bugs, misconfigurations, untuned settings.
Filesystem CorruptionCaused by improper shutdown or hardware failure. Repair: fsck /dev/sda1 (unmounted only). xfs_repair /dev/sdb1 for XFS.
Kernel PanicLinux equivalent of BSOD. System cannot safely recover. Causes: corrupted kernel, missing root filesystem, hardware failure, incompatible modules. Check dmesg logs after recovery.
Inode ExhaustionFilesystem runs out of inodes before running out of disk space. Caused by millions of tiny files (email queues, temp files, cache). Symptoms: "No space left on device" but df -h shows free space. Diagnose: df -i shows inode usage. Fix: delete many small files or reformat with more inodes.
Filesystem Full (OS)/ or /var full causes widespread service failures (logs can't write, daemons can't create temp files). Check: df -h. Find large files: du -sh /* | sort -rh | head. Clean logs, old kernels, core dumps.
Quota IssuesUser or group has exceeded disk quota. Symptoms: user cannot write files despite available disk space. Check: quota -u username or repquota /filesystem. Increase quota or ask user to delete files.
Partition Not WritableMounted read-only. Common after filesystem error — kernel remounts read-only to prevent further damage. Check /proc/mounts. Fix: remount rw after fsck repairs the filesystem.
GRUB MisconfigurationSystem fails to boot or boots wrong OS. Symptoms: GRUB prompt, "error: unknown filesystem", missing menu entries. Fix from live media: mount root filesystem, chroot, reinstall GRUB (grub2-install) and regenerate config (grub2-mkconfig).
Missing/Disabled DriversHardware not detected or not functional. Check: dmesg | grep -i error, lspci -v for missing drivers. Load with modprobe or install driver package.
Killed ProcessesProcess terminated unexpectedly. Check: OOM killer (dmesg | grep -i killed), audit log (ausearch), systemd journal. OOM kills = system needed memory. Fix: add RAM, tune OOM score, reduce memory usage.
Segmentation FaultProcess accessed memory it shouldn't. Causes: bugs in code, corrupted binary, wrong library version, hardware memory errors. Check: dmesg, core dump, strace output.
systemctl status servicename. View logs: journalctl -u servicename. Check service dependencies. Verify config syntax. Port conflicts: ss -tlnp.
PATH MisconfigurationCommands not found or wrong version executing. Check: echo $PATH. Which binary: which command. Add to PATH: export PATH=$PATH:/new/dir. Make persistent in ~/.bashrc. Common issue after software installs in non-standard locations.
Unresponsive ProcessProcess in D state (uninterruptible sleep) — usually waiting on I/O. Cannot be killed with SIGKILL. Usually resolves when I/O completes or fails. Check: ps aux | grep " D ". Causes: NFS hang, disk failure, kernel bug.
Package Dependency IssuesPackage cannot install due to missing or conflicting dependencies. Fix: apt --fix-broken install (Debian) or dnf install --best (RHEL). For conflicts: remove conflicting package first.
Systemd Unit FailuresService fails to start. Check: systemctl status unit for recent output. journalctl -xe -u unit for detailed logs. Common causes: missing binary, permission denied, port already in use, syntax error in unit file.
File IntegrityRPM: rpm -V package verifies files against package database. Tripwire/AIDE: IDS tools that hash system files and alert on changes.
Clock SkewKerberos fails if clock skew >5 minutes. Sync: timedatectl set-ntp true. Check: timedatectl status.
Memory LeaksProcess continuously consuming more memory without releasing it. Symptoms: gradually increasing memory use in top/htop, growing RSS over time. Resolve by restarting the process. Report bug to developers. Use Valgrind for debugging.
vmstat 1 (watch si/so columns), free -h. Fix: add RAM, kill memory hogs, tune application heap sizes.
High Load AverageLoad average consistently above number of CPU cores = system is overloaded. Check: uptime or top header. May be CPU-bound or I/O-bound — distinguish with iostat and top.
High Context SwitchingMany processes competing for CPU. Wastes CPU cycles on switching overhead. Check with vmstat 1 (cs column) or pidstat -w.
High I/O WaitCPU idle while waiting for disk I/O. Shows as high %wa in top/iostat. Indicates storage bottleneck. Check: iostat -x for device utilization and await times. Solutions: faster storage, I/O scheduler tuning, caching.
High Disk LatencyStorage operations taking longer than expected. Check with iostat -x (await column). Causes: failing drive (check SMART), RAID degradation, overloaded SAN, filesystem fragmentation (HDD only).
CPU BottleneckCPU consistently at 100%. Identify: top → look for process consuming most CPU. Causes: inefficient code, insufficient CPUs, runaway process. Solutions: optimize code, add vCPUs, nice/renice processes.
Blocked ProcessesProcesses in D state waiting for I/O that never completes. Usually storage-related. ps aux | awk '$8=="D"'. Often caused by NFS mount hangs or failing disks.
Memory LeaksProcess continuously consuming more RAM without releasing it. RSS grows continuously in top. Restart the process as workaround. Report to developers.
Slow Application ResponseStart with: CPU, memory, disk I/O, and network checks. Then move to application-level: database query performance, connection pool exhaustion, external dependency latency.
Slow Remote StorageNFS or SMB mounts responding slowly. Check network path (mtr), NFS server load, mount options (noatime helps), network bandwidth (iperf3).
Packet Drops / JitterNetwork performance degradation. Packet drops: ip -s link show eth0 (check RX errors/drops). Jitter: use mtr to see per-hop latency variance. Causes: buffer overflow, hardware issue, oversubscribed links.
ss -tlnp (is service listening?). firewall-cmd --list-all or iptables -L (is port open?). Test locally first — if local works but remote doesn't = firewall issue.
DHCP IssuesClient gets APIPA (169.254.x.x) or wrong IP. Check: DHCP server running? journalctl -u dhcpd. Scope exhausted? Client can reach DHCP server? Check DHCP relay if across subnets.
DNS IssuesName resolution fails. Can ping IP but not hostname = DNS problem. Check /etc/resolv.conf (correct nameserver?). Test: dig @8.8.8.8 example.com (bypass local DNS). Check nsswitch.conf resolution order.
MTU MismatchPackets fragmented or dropped. Common with VPNs and tunnels. Symptoms: small packets work, large packets fail. Check: ip link show (MTU field). Test: ping -M do -s 1400 host. Fix: set MTU lower on interface or VPN config.
NIC Bonding IssuesBonded NIC not failover or load balancing correctly. Check bonding mode, member link states, LACP negotiation. cat /proc/net/bonding/bond0 shows status.
MAC SpoofingUnauthorized device using a legitimate MAC address. Causes IP conflicts and authentication bypass. Detect with ARP monitoring, port security on switches.
IP ConflictsTwo devices with the same IP. Symptoms: intermittent connectivity. Check: arp -n — same IP mapping to different MACs. Use arping to identify the conflicting device.
Dual-Stack Issues (IPv4/IPv6)IPv4 works but IPv6 doesn't (or vice versa). Check both: ping vs ping6, ip -4 addr vs ip -6 addr. DNS may return AAAA records for IPv6-only or IPv4-only services causing failures.
Link Downip link show shows DOWN state. Physical: check cable, SFP, switch port. Virtual: check NIC driver, VM network config. Bring up: ip link set eth0 up.
Link Negotiation IssuesSpeed/duplex mismatch. Symptoms: slow speeds, high errors, runts. Check: ethtool eth0 (Speed and Duplex fields). Fix: force both ends to matching settings or enable auto-negotiation on both.
ip link show. Look for UP/DOWN status. Check cable and NIC.ip addr. Confirm correct IP, subnet mask, and gateway. Check for APIPA address (169.254.x.x = DHCP failure).ping [gateway IP]. If fails = local network issue. If succeeds = upstream problem.ping 8.8.8.8. If fails with gateway success = routing/ISP issue.ping google.com. Failure with successful IP ping = DNS issue. Diagnose with dig or nslookup.traceroute / mtr to identify where packets are dropping.tcpdump or Wireshark for deep packet analysis if above steps are inconclusive.