Debian is one of the oldest and most influential Linux distributions, first announced on August 16, 1993 by Ian Murdock on the comp.os.linux.development newsgroup.
The name “Debian” is a portmanteau of Debra (his girlfriend at the time, later wife) and Ian Murdock.
Version 0.01 was released in September 1993; the first stable release 1.1 “Buzz” arrived in June 1996.
Debian introduced the Debian Free Software Guidelines (DFSG) — a set of principles defining what constitutes free software, which later became the basis for the Open Source Definition.
The Debian Social Contract was written in 1997, committing the project to always remain free and to give back to the free software community.
Debian releases are named after characters from Toy Story — a tradition started because Bruce Perens (second Debian leader) worked at Pixar.
Who
Founded by Ian Murdock (1973–2015) — a visionary who wanted a distribution built openly, in the spirit of Linux and GNU.
Maintained by the Debian Project — a global volunteer organization with no corporate sponsor.
Governed by the Debian Constitution and led by a democratically elected Debian Project Leader (DPL).
Over 1,000 active Debian Developers (DDs) and Debian Maintainers (DMs) worldwide.
Key figures: Ian Murdock (founder), Bruce Perens (2nd leader), Wichert Akkerman, Sam Hartman, Jonathan Carter (recent DPL).
Why
Ian Murdock was frustrated with existing distributions that were not developed openly or collaboratively.
Goal: create a distribution that would be maintained openly, in the spirit of Linux and GNU — a true community project.
Debian was designed to be the universal operating system — supporting more hardware architectures than any other distro.
The DFSG and Social Contract ensure Debian remains committed to freedom, transparency, and quality.
Debian’s stability and reliability made it the foundation for hundreds of downstream distributions, most notably Ubuntu, Kali Linux, Linux Mint, Raspberry Pi OS, and MX Linux.
Introduction
What is Debian?
Debian GNU/Linux is a free, community-driven, universal operating system built entirely on free software.
Uses DEB packages managed by APT (Advanced Package Tool) — one of the most mature package management systems in Linux.
Supports 13+ CPU architectures: amd64, arm64, armel, armhf, i386, mips64el, mipsel, ppc64el, s390x, and more.
Available in three main flavors: Desktop (GNOME, KDE, Xfce, LXDE, MATE, Cinnamon), Server (minimal CLI), and Live (try without installing).
Debian is the upstream source for Ubuntu, Kali Linux, and hundreds of other distributions.
Debian Editions
Debian Desktop → Full desktop environment (GNOME default, others available)
Debian Server → Minimal CLI install, no GUI, ideal for servers
Debian Live → Try Debian without installing (boots from USB/DVD)
Debian Netinstall → Minimal ISO (~400MB), downloads packages during install
Debian Cloud → Official images for AWS, Azure, GCP, OpenStack
Debian Embedded → For embedded/IoT devices (arm, mips)
Exceptional stability (Stable branch), massive package repository (59,000+ packages), supports more architectures than any other distro, strong commitment to free software, no corporate control, excellent security track record, long support cycles, rock-solid APT dependency resolution, foundation for hundreds of distros, highly customizable, great for servers and embedded systems.
Disadvantages
Stable branch has older packages (by design), no sudo by default (must configure manually), installer is less user-friendly than Ubuntu, non-free firmware not included by default (improving in Debian 12+), slower to adopt new features, smaller desktop market share than Ubuntu, less beginner-friendly out of the box.
Use Cases
Production servers (web, database, mail), Raspberry Pi and embedded systems, security research base (Kali Linux is Debian-based), long-running stable desktops, CI/CD build environments, Docker base images (debian:bookworm-slim), cloud infrastructure, NAS/home lab servers, academic and research computing.
# Using dd (Linux/macOS)sudo dd if=debian-12.x.x-amd64-netinst.iso of=/dev/sdX bs=4M status=progresssync# Using Ventoy (multi-boot USB)# Just copy the ISO to the Ventoy USB drive# Using Balena Etcher (GUI, cross-platform)# Download from: https://etcher.balena.io
Debian Installer Steps
1. Boot from USB → "Graphical Install" (recommended) or "Install" (text)
2. Language → Country → Keyboard layout
3. Hostname (e.g., debian-server) → Domain name (optional)
4. Root password → Create non-root user + password
5. Partition disks:
- Guided (entire disk) → recommended for beginners
- Manual: /boot/efi (512MB, EFI), /boot (1GB, ext4),
swap (2×RAM or 4GB), / (rest, ext4 or btrfs)
6. Configure package manager:
- Select mirror country → choose mirror (deb.debian.org recommended)
- HTTP proxy (leave blank if none)
7. Popularity contest → optional (helps Debian stats)
8. Software selection:
- [*] Debian desktop environment
- [*] GNOME (or KDE, Xfce, etc.)
- [*] SSH server (for servers)
- [*] Standard system utilities
9. Install GRUB → select disk (/dev/sda or /dev/nvme0n1)
10. Reboot → remove USB
First Boot Configuration
# Switch to root (Debian doesn't add your user to sudo by default!)su -# Install sudo and add your userapt install sudousermod -aG sudo yourusername# Log out and back in for group change to take effect# Update package lists and upgradesudo apt update && sudo apt upgrade -y# Enable contrib and non-free repos (for firmware, codecs, etc.)sudo nano /etc/apt/sources.list# Change:# deb http://deb.debian.org/debian bookworm main# To:# deb http://deb.debian.org/debian bookworm main contrib non-free non-free-firmwaresudo apt update# Install common toolssudo apt install -y curl wget git vim htop net-tools build-essential# Install firmware (if needed)sudo apt install -y firmware-linux firmware-linux-nonfree# Check system infouname -r # kernel versionlsb_release -a # Debian version infohostnamectl # hostname and OS info
Default Filesystem Layout
Debian default partition layout (ext4):
/boot/efi → EFI System Partition (FAT32, ~512MB) — UEFI only
/boot → Kernel + initrd (ext4, ~1GB)
swap → Swap partition (2×RAM recommended)
/ → Root filesystem (ext4, rest of disk)
Optional separate partitions (server best practice):
/home → User data (separate for easy reinstall)
/var → Logs, databases (prevents root fill-up)
/tmp → Temporary files (can be tmpfs)
/srv → Service data
Key directories:
/etc → All system configuration
/var/log → System logs
/var/cache/apt → APT package cache
/usr → Programs and libraries
/opt → Third-party software
Kernel & Architecture
Linux Kernel on Debian
Debian Stable ships a Long-Term Support (LTS) kernel — stable and well-tested, not bleeding edge.
Debian 12 (Bookworm) ships Linux 6.1 LTS.
Debian Testing/Sid ships newer kernels, closer to upstream.
Kernel packages: linux-image-amd64 (meta-package, always latest for your arch).
# Check current kerneluname -r # e.g., 6.1.0-21-amd64uname -a # full infocat /proc/version # kernel + compiler info# List installed kernelsdpkg -l | grep linux-imagels /boot/vmlinuz*# Install a specific kernelsudo apt install linux-image-6.1.0-21-amd64# Install latest kernel meta-packagesudo apt install linux-image-amd64# Install kernel headers (needed for building modules)sudo apt install linux-headers-$(uname -r)sudo apt install linux-headers-amd64# Remove old kernels (apt autoremove handles this)sudo apt autoremove# Kernel messagesdmesg | head -50dmesg -T | grep -i errorjournalctl -k # kernel log via systemd
Boot Process
graph TD
A["🔌 Power On"] --> B["UEFI/BIOS POST\nHardware initialization"]
B --> C["GRUB2 Bootloader\n/boot/grub/grub.cfg"]
C --> D["Kernel loads\nvmlinuz-6.1.0-amd64"]
D --> E["initramfs mounts\nearly root filesystem\n(initrd.img)"]
E --> F["Kernel detects hardware\nloads essential drivers"]
F --> G["systemd starts\nPID 1"]
G --> H["sysinit.target\nmount filesystems, udev"]
H --> I["basic.target\nlogging, sockets"]
I --> J{Boot target?}
J -->|Server| K["multi-user.target\nCLI login prompt"]
J -->|Desktop| L["graphical.target\nGDM/LightDM login"]
Linux FHS Layout on Debian
/ Root filesystem (ext4 default on Debian)
├── /bin → symlink to /usr/bin (UsrMerge in Debian 12+)
├── /boot Kernel (vmlinuz), initrd, GRUB2 files
│ └── /boot/efi EFI partition (UEFI systems)
├── /dev Device files (managed by udev)
├── /etc System-wide configuration files
│ ├── /etc/apt APT configuration + sources.list
│ ├── /etc/network Network interfaces (ifupdown)
│ ├── /etc/systemd Systemd unit files
│ └── /etc/ssh SSH server config
├── /home User home directories
├── /lib → symlink to /usr/lib
├── /lib64 → symlink to /usr/lib64
├── /media Auto-mounted removable media
├── /mnt Manual mount points
├── /opt Optional third-party software
├── /proc Virtual: process + kernel info (procfs)
├── /root Root user's home directory
├── /run Runtime data (cleared on reboot, tmpfs)
├── /sbin → symlink to /usr/sbin
├── /srv Service data (web, ftp)
├── /sys Virtual: hardware/driver info (sysfs)
├── /tmp Temporary files (tmpfs or ext4)
├── /usr All user programs, libraries, docs
│ ├── /usr/bin User commands
│ ├── /usr/sbin Admin commands
│ ├── /usr/lib Shared libraries
│ ├── /usr/share Architecture-independent data, man pages
│ └── /usr/local Locally installed software (not from apt)
└── /var Variable data
├── /var/log System logs
├── /var/cache Package cache (/var/cache/apt)
├── /var/lib Application state data
└── /var/spool Mail, print queues
GRUB2 Management
# View current GRUB configcat /boot/grub/grub.cfg# Edit GRUB defaultssudo nano /etc/default/grub# Key options:# GRUB_DEFAULT=0 # default boot entry (0 = first)# GRUB_TIMEOUT=5 # seconds to show menu# GRUB_CMDLINE_LINUX_DEFAULT="quiet splash" # kernel params# GRUB_CMDLINE_LINUX="" # always-applied params# Regenerate GRUB config after changessudo update-grub# or explicitly:sudo grub-mkconfig -o /boot/grub/grub.cfg# Reinstall GRUB to MBR (if bootloader is broken)sudo grub-install /dev/sda# Reinstall GRUB for UEFIsudo grub-install --target=x86_64-efi --efi-directory=/boot/efisudo update-grub# List GRUB entriesgrep -E "^menuentry|^submenu" /boot/grub/grub.cfg
APT Package Management
What is APT?
APT (Advanced Package Tool) is Debian’s high-level package management system, introduced in 1998.
Works on top of dpkg (the low-level package tool) — APT handles dependency resolution, dpkg handles actual installation.
graph TD
U["👤 User runs apt install pkg"] --> A["APT reads sources.list"]
A --> B["Downloads package index\n/var/lib/apt/lists/"]
B --> C["Resolves dependencies\n(recursive)"]
C --> D{All deps available?}
D -->|No| E["❌ Dependency error\nshow conflict"]
D -->|Yes| F["Downloads .deb files\n/var/cache/apt/archives/"]
F --> G["Calls dpkg\nto install each .deb"]
G --> H["dpkg unpacks\nconfigures package"]
H --> I["Runs maintainer scripts\npreinst, postinst"]
I --> J["✅ Package installed\n/var/lib/dpkg/status updated"]
Essential APT Commands
# ── Update & Upgrade ──────────────────────────────────────────sudo apt update # refresh package index (always run first)sudo apt upgrade -y # upgrade all upgradable packagessudo apt full-upgrade -y # upgrade + handle dependency changes (dist-upgrade)sudo apt dist-upgrade -y # same as full-upgrade (older alias)# ── Install & Remove ──────────────────────────────────────────sudo apt install package # install a packagesudo apt install pkg1 pkg2 pkg3 # install multiple packagessudo apt install ./local.deb # install local .deb filesudo apt install package=1.2.3 # install specific versionsudo apt remove package # remove package (keep config files)sudo apt purge package # remove package + config filessudo apt autoremove # remove unused dependenciessudo apt autoremove --purge # remove unused deps + their configs# ── Search & Info ─────────────────────────────────────────────apt search keyword # search packages by name/descriptionapt show package # show package detailsapt list --installed # list all installed packagesapt list --upgradable # list upgradable packagesapt list --all-versions package # list all available versions# ── Cache Management ──────────────────────────────────────────sudo apt clean # remove all cached .deb filessudo apt autoclean # remove only outdated cached .debsdu -sh /var/cache/apt/archives/ # check cache size# ── Fix Broken Packages ───────────────────────────────────────sudo apt install -f # fix broken dependenciessudo apt --fix-broken install # same as abovesudo dpkg --configure -a # configure any unconfigured packages
APT-Cache Commands
apt-cache search keyword # search package names + descriptionsapt-cache show package # detailed package infoapt-cache showpkg package # show dependencies + reverse depsapt-cache depends package # show what package depends onapt-cache rdepends package # show what depends on packageapt-cache policy package # show installed vs candidate versionapt-cache stats # overall cache statisticsapt-cache pkgnames # list all known package namesapt-cache pkgnames | grep nginx # find packages matching pattern
APT-Mark Commands
sudo apt-mark hold package # prevent package from being upgradedsudo apt-mark unhold package # allow package to be upgraded againsudo apt-mark auto package # mark as auto-installed (autoremovable)sudo apt-mark manual package # mark as manually installed (keep)apt-mark showhold # list held packagesapt-mark showauto # list auto-installed packagesapt-mark showmanual # list manually installed packages
dpkg Commands
# ── Install / Remove ──────────────────────────────────────────sudo dpkg -i package.deb # install a .deb filesudo dpkg -r package # remove package (keep configs)sudo dpkg -P package # purge package + configssudo dpkg --configure -a # configure all unconfigured packages# ── Query ─────────────────────────────────────────────────────dpkg -l # list all installed packagesdpkg -l | grep nginx # filter installed packagesdpkg -l package # status of specific packagedpkg -s package # show package status + infodpkg -L package # list files installed by packagedpkg -S /path/to/file # which package owns this filedpkg --get-selections # list all packages with statusdpkg --print-architecture # show system architecture# ── Verify ────────────────────────────────────────────────────dpkg -V package # verify package file integritydpkg -V # verify all installed packages
sources.list Explained
# /etc/apt/sources.list format:# deb [options] URI suite component1 component2 ...# ── Debian 12 Bookworm (full recommended) ────────────────────deb http://deb.debian.org/debian bookworm main contrib non-free non-free-firmwaredeb-src http://deb.debian.org/debian bookworm main contrib non-free non-free-firmware# Security updates (critical — always include)deb http://security.debian.org/debian-security bookworm-security main contrib non-free non-free-firmwaredeb-src http://security.debian.org/debian-security bookworm-security main contrib non-free non-free-firmware# Stable updates (bug fixes, not security)deb http://deb.debian.org/debian bookworm-updates main contrib non-free non-free-firmwaredeb-src http://deb.debian.org/debian bookworm-updates main contrib non-free non-free-firmware# Components explained:# main → Free software (DFSG-compliant), officially supported# contrib → Free software that depends on non-free packages# non-free → Non-free software (proprietary)# non-free-firmware → Firmware blobs (Wi-Fi, GPU) — new in Debian 12
Debian uses bash (Bourne Again Shell) as the default login shell for users.
/bin/sh on Debian points to dash (not bash) — a POSIX-compliant, faster shell used for system scripts.
Other available shells: zsh, fish, tcsh, ksh — install via apt.
echo $SHELL # current shellcat /etc/shells # all available shellschsh -s /bin/zsh # change default shell (re-login required)ls -la /bin/sh # shows sh → dash on Debian
Essential Commands
# ── Navigation ────────────────────────────────────────────────pwd # print working directoryls -la # list files (long format, hidden)ls -lh # human-readable sizescd /path/to/dir # change directorycd ~ # go to home directorycd - # go to previous directory# ── File Operations ───────────────────────────────────────────touch file.txt # create empty file / update timestampcp source dest # copy filecp -r source/ dest/ # copy directory recursivelymv source dest # move / renamerm file.txt # delete filerm -rf directory/ # delete directory recursively (careful!)mkdir -p /path/to/new/dir # create directory + parents# ── View Files ────────────────────────────────────────────────cat file.txt # print file contentsless file.txt # paginated view (q to quit)head -n 20 file.txt # first 20 linestail -n 20 file.txt # last 20 linestail -f /var/log/syslog # follow log in real-time# ── Search ────────────────────────────────────────────────────grep "pattern" file.txt # search in filegrep -r "pattern" /etc/ # recursive searchgrep -i "pattern" file.txt # case-insensitivefind / -name "*.conf" 2>/dev/null # find files by namefind /var -size +100M # find files larger than 100MBlocate filename # fast search (needs updatedb)which command # find command location# ── System Info ───────────────────────────────────────────────uname -a # kernel + system infolsb_release -a # Debian versionhostnamectl # hostname + OS infouptime # system uptime + loadfree -h # memory usagedf -h # disk usagedu -sh /var/log/ # directory sizelscpu # CPU infolsblk # block deviceslspci # PCI deviceslsusb # USB devices# ── Process Management ────────────────────────────────────────ps aux # all running processesps aux | grep nginx # find specific processtop # interactive process viewerhtop # better interactive viewer (install: apt install htop)kill PID # send SIGTERM to processkill -9 PID # send SIGKILL (force kill)killall nginx # kill all processes named nginxpkill -f "pattern" # kill by pattern matchnice -n 10 command # run with lower priorityrenice -n 5 -p PID # change priority of running process# ── Disk & Filesystem ─────────────────────────────────────────mount /dev/sdb1 /mnt # mount deviceumount /mnt # unmountfdisk -l # list partitionslsblk -f # list block devices + filesystemsblkid # show UUIDs of block devices
File Permissions
# Permission format: [type][owner][group][others]# Example: -rwxr-xr-- 1 alice devs 4096 Jan 1 12:00 script.sh# d = directory, - = file, l = symlink# r=4, w=2, x=1chmod 755 script.sh # rwxr-xr-x (owner: rwx, group: rx, others: rx)chmod 644 file.txt # rw-r--r-- (owner: rw, group: r, others: r)chmod 600 ~/.ssh/id_rsa # rw------- (private key — must be 600)chmod +x script.sh # add execute for allchmod -R 755 /var/www/html/ # recursivechown user:group file.txt # change owner + groupchown -R www-data:www-data /var/www/html/chgrp devs project/ # change group only# Special permissionschmod u+s /usr/bin/program # setuid — runs as file ownerchmod g+s /shared/dir/ # setgid — new files inherit groupchmod +t /tmp/ # sticky bit — only owner can delete# View permissionsls -la file.txtstat file.txt # detailed file info including permissions# umask — default permission maskumask # show current umask (e.g., 0022)umask 027 # set umask (files: 640, dirs: 750)
I/O Redirection
command > file.txt # redirect stdout to file (overwrite)command >> file.txt # redirect stdout to file (append)command 2> error.log # redirect stderr to filecommand 2>&1 # redirect stderr to stdoutcommand > output.txt 2>&1 # redirect both stdout + stderrcommand &> output.txt # same (bash shorthand)command < input.txt # redirect stdin from filecommand1 | command2 # pipe stdout of cmd1 to stdin of cmd2command | tee file.txt # pipe + write to file simultaneouslycommand > /dev/null 2>&1 # discard all output# Here documentcat << EOF > config.txtline 1line 2EOF# Process substitutiondiff <(ls dir1) <(ls dir2) # compare outputs of two commands
Shell Scripting Basics
#!/bin/bash# Shebang line — always first line of script# VariablesNAME="Debian"VERSION=12echo "Welcome to $NAME $VERSION"# Command substitutionKERNEL=$(uname -r)echo "Kernel: $KERNEL"# Conditionalsif [ -f /etc/debian_version ]; then echo "This is Debian"elif [ -f /etc/fedora-release ]; then echo "This is Fedora"else echo "Unknown distro"fi# Loopsfor pkg in curl wget git vim; do sudo apt install -y "$pkg"done# While loopCOUNT=0while [ $COUNT -lt 5 ]; do echo "Count: $COUNT" ((COUNT++))done# Functionsinstall_pkg() { local pkg="$1" if dpkg -l "$pkg" &>/dev/null; then echo "$pkg already installed" else sudo apt install -y "$pkg" fi}install_pkg nginx# Exit codescommand && echo "success" || echo "failed"exit 0 # successexit 1 # failure
User & Group Management
Account Types
root → UID 0, superuser, full system access
System users → UID 1-999, for services (www-data, mysql, nobody)
Regular users → UID 1000+, human users
useradd vs adduser
# adduser — Debian's friendly user creation toolsudo adduser alice # interactive: prompts for password, name, etc.sudo adduser alice sudo # add alice to sudo groupsudo adduser alice www-data # add alice to www-data group# useradd — low-level, non-interactivesudo useradd -m -s /bin/bash -c "Alice Smith" alice # -m=home, -s=shellsudo useradd -r -s /usr/sbin/nologin serviceuser # system user, no loginsudo passwd alice # set password separately# Modify usersudo usermod -aG sudo alice # add to group (append, don't replace)sudo usermod -s /bin/zsh alice # change shellsudo usermod -l newname oldname # rename usersudo usermod -L alice # lock accountsudo usermod -U alice # unlock accountsudo usermod -e 2025-12-31 alice # set account expiry# Delete usersudo deluser alice # remove user (keep home dir)sudo deluser --remove-home alice # remove user + home dirsudo userdel -r alice # low-level equivalent# User infoid alice # UID, GID, groupswhoami # current userwho # logged-in usersw # logged-in users + activitylast # login historyfinger alice # user info (install: apt install finger)cat /etc/passwd # all user accountsgetent passwd alice # user entry from passwd database
sudo Setup on Debian
# Step 1: Switch to rootsu -# Step 2: Install sudo (may not be installed)apt install sudo# Step 3: Add user to sudo groupusermod -aG sudo yourusername# OR edit sudoers directly:adduser yourusername sudo# Step 4: Log out and back in (or use newgrp)newgrp sudo# Verifygroups yourusername # should show sudo in listsudo whoami # should return "root"
/etc/sudoers Configuration
# Always edit sudoers with visudo (validates syntax before saving)sudo visudo# /etc/sudoers format:# user host=(runas) commands# Allow alice to run all commands as rootalice ALL=(ALL:ALL) ALL# Allow alice to run all commands without passwordalice ALL=(ALL:ALL) NOPASSWD: ALL# Allow alice to run only specific commandsalice ALL=(ALL) /usr/bin/apt, /usr/bin/systemctl# Allow group sudo to run all commands (default Debian config)%sudo ALL=(ALL:ALL) ALL# Drop-in files (preferred over editing sudoers directly)sudo visudo -f /etc/sudoers.d/alice# Contents:alice ALL=(ALL:ALL) NOPASSWD: /usr/bin/apt update, /usr/bin/apt upgrade
Group Management
# Create / delete groupssudo groupadd developers # create groupsudo groupdel developers # delete groupsudo groupmod -n devs developers # rename group# Add / remove users from groupssudo usermod -aG developers alice # add alice to developers (-a = append!)sudo gpasswd -d alice developers # remove alice from developerssudo gpasswd -A alice developers # make alice group admin# View groupsgroups # current user's groupsgroups alice # alice's groupscat /etc/group # all groupsgetent group developers # group entry# Important system groups on Debian:# sudo → sudo access# www-data → web server (Apache/Nginx)# docker → Docker access (no sudo needed)# adm → read system logs# dialout → serial ports# plugdev → USB/removable media
Password & Account Policies
# Password managementpasswd # change own passwordsudo passwd alice # change alice's passwordsudo passwd -l alice # lock alice's passwordsudo passwd -u alice # unlock alice's passwordsudo passwd -e alice # expire password (force change on next login)# Password aging (chage)sudo chage -l alice # show password aging infosudo chage -M 90 alice # max 90 days before password expiressudo chage -m 7 alice # min 7 days between changessudo chage -W 14 alice # warn 14 days before expirysudo chage -E 2025-12-31 alice # account expires on date# /etc/login.defs — system-wide defaultsgrep -E "^PASS_MAX_DAYS|^PASS_MIN_DAYS|^PASS_WARN_AGE" /etc/login.defs
Systemd & Service Management
systemctl Commands
# ── Service Control ───────────────────────────────────────────sudo systemctl start nginx # start servicesudo systemctl stop nginx # stop servicesudo systemctl restart nginx # stop + startsudo systemctl reload nginx # reload config (no downtime)sudo systemctl enable nginx # enable at bootsudo systemctl disable nginx # disable at bootsudo systemctl enable --now nginx # enable + start immediatelysudo systemctl disable --now nginx # disable + stop immediately# ── Status & Info ─────────────────────────────────────────────systemctl status nginx # service status + recent logssystemctl is-active nginx # active / inactivesystemctl is-enabled nginx # enabled / disabledsystemctl is-failed nginx # failed / not-failedsystemctl list-units # all active unitssystemctl list-units --type=service # all active servicessystemctl list-units --state=failed # all failed unitssystemctl list-unit-files # all installed unit files + statesystemctl list-unit-files --type=service# ── System State ──────────────────────────────────────────────sudo systemctl reboot # reboot systemsudo systemctl poweroff # shut downsudo systemctl halt # halt (no power off)sudo systemctl suspend # suspend to RAMsudo systemctl hibernate # suspend to disk# ── Targets (runlevels) ───────────────────────────────────────systemctl get-default # current default targetsudo systemctl set-default multi-user.target # set default to CLIsudo systemctl set-default graphical.target # set default to GUIsudo systemctl isolate rescue.target # switch to rescue mode# ── Daemon reload ─────────────────────────────────────────────sudo systemctl daemon-reload # reload unit files after editing
journalctl Commands
# ── View Logs ─────────────────────────────────────────────────journalctl # all logs (oldest first)journalctl -r # reverse (newest first)journalctl -f # follow (like tail -f)journalctl -n 50 # last 50 linesjournalctl -b # logs since last bootjournalctl -b -1 # logs from previous bootjournalctl --since "2024-01-01" # logs since datejournalctl --since "1 hour ago" # logs from last hourjournalctl --until "2024-01-02 12:00"# ── Filter by Unit ────────────────────────────────────────────journalctl -u nginx # logs for nginx servicejournalctl -u nginx -f # follow nginx logsjournalctl -u nginx --since today # nginx logs todayjournalctl -u ssh -u nginx # multiple units# ── Filter by Priority ────────────────────────────────────────journalctl -p err # errors onlyjournalctl -p warning # warnings + abovejournalctl -p 0..3 # emerg, alert, crit, err# Priorities: 0=emerg, 1=alert, 2=crit, 3=err, 4=warning, 5=notice, 6=info, 7=debug# ── Kernel Logs ───────────────────────────────────────────────journalctl -k # kernel messages onlyjournalctl -k -b # kernel messages this boot# ── Disk Usage ────────────────────────────────────────────────journalctl --disk-usage # journal disk usagesudo journalctl --vacuum-size=500M # keep only 500MB of logssudo journalctl --vacuum-time=30d # keep only last 30 days
# Enable and start the servicesudo systemctl daemon-reloadsudo systemctl enable --now myappsudo systemctl status myappjournalctl -u myapp -f
Networking
Network Stack Diagram
graph TD
APP["Application Layer\ncurl, ssh, nginx, browser"]
SOCK["Socket API\nsocket(), bind(), connect()"]
TCP["Transport Layer\nTCP / UDP"]
IP["Network Layer\nIP routing, iptables/nftables"]
ETH["Data Link Layer\nEthernet, Wi-Fi (802.11)"]
HW["Physical Layer\nNIC, Cable, Wi-Fi adapter"]
APP --> SOCK
SOCK --> TCP
TCP --> IP
IP --> ETH
ETH --> HW
NM["NetworkManager\nor systemd-networkd"] -.->|configures| ETH
FW["nftables / iptables / ufw"] -.->|filters| IP
ip & ss Commands
# ── Interface Management (ip) ─────────────────────────────────ip addr # show all interfaces + IPsip addr show eth0 # show specific interfaceip link # show link stateip link set eth0 up # bring interface upip link set eth0 down # bring interface down# Add/remove IP addresssudo ip addr add 192.168.1.100/24 dev eth0sudo ip addr del 192.168.1.100/24 dev eth0# ── Routing ───────────────────────────────────────────────────ip route # show routing tableip route show # samesudo ip route add default via 192.168.1.1 # add default gatewaysudo ip route add 10.0.0.0/8 via 192.168.1.1 # add static routesudo ip route del 10.0.0.0/8 # delete route# ── Socket Statistics (ss) ────────────────────────────────────ss -tuln # TCP+UDP listening ports (numeric)ss -tulnp # + process namesss -s # summary statisticsss -ta # all TCP connectionsss -ua # all UDP connectionsss -tp # TCP + process infoss -o state established # established connections only# ── DNS ───────────────────────────────────────────────────────cat /etc/resolv.conf # DNS serverscat /etc/hosts # local hostname resolutionhost google.com # DNS lookupnslookup google.com # DNS lookup (interactive)dig google.com # detailed DNS querydig google.com MX # MX recordsdig @8.8.8.8 google.com # query specific DNS server# ── Connectivity ──────────────────────────────────────────────ping -c 4 8.8.8.8 # ICMP ping (4 packets)traceroute google.com # trace route (install: apt install traceroute)mtr google.com # combined ping + traceroute (apt install mtr)curl -I https://example.com # HTTP headerswget -q -O /dev/null https://example.com # test downloadnc -zv 192.168.1.1 22 # test TCP port connectivity# ── Legacy (net-tools — install separately) ───────────────────sudo apt install net-toolsifconfig # old interface info (use ip addr instead)netstat -tuln # old socket info (use ss instead)route -n # old routing table (use ip route instead)
NetworkManager vs systemd-networkd
Feature
NetworkManager
systemd-networkd
Best for
Desktops, laptops, Wi-Fi
Servers, containers, static configs
Config files
/etc/NetworkManager/
/etc/systemd/network/*.network
CLI tool
nmcli
networkctl
GUI
nm-applet, GNOME
None
Wi-Fi support
Excellent
Limited
DHCP
Built-in
systemd-networkd + systemd-resolved
Default on
Debian Desktop
Debian Server (minimal)
# NetworkManager CLI (nmcli)nmcli device status # show all devicesnmcli connection show # show all connectionsnmcli connection up "Wired connection 1"nmcli connection down "Wired connection 1"nmcli device wifi list # list Wi-Fi networksnmcli device wifi connect "SSID" password "password"nmcli connection add type ethernet ifname eth0 con-name myconn \ ipv4.addresses 192.168.1.100/24 ipv4.gateway 192.168.1.1 \ ipv4.dns "8.8.8.8 8.8.4.4" ipv4.method manual
# Installsudo apt install aide aide-common# Initialize database (takes a few minutes)sudo aideinitsudo cp /var/lib/aide/aide.db.new /var/lib/aide/aide.db# Run integrity checksudo aide --check# Update database after legitimate changessudo aide --updatesudo cp /var/lib/aide/aide.db.new /var/lib/aide/aide.db# Automate with cronecho "0 3 * * * root /usr/bin/aide --check | mail -s 'AIDE Report' admin@example.com" | \ sudo tee /etc/cron.d/aide-check
Lynis Security Audit
# Installsudo apt install lynis# Run full system auditsudo lynis audit system# Run specific testssudo lynis audit system --tests-from-group authenticationsudo lynis audit system --tests-from-group networking# View reportcat /var/log/lynis.logcat /var/log/lynis-report.dat# Lynis hardening index: aim for 80+grep "hardening_index" /var/log/lynis-report.dat
Privilege Escalation Checks
# Find SUID/SGID binaries (potential escalation vectors)find / -perm -4000 -type f 2>/dev/null # SUID filesfind / -perm -2000 -type f 2>/dev/null # SGID filesfind / -perm -6000 -type f 2>/dev/null # SUID + SGID# Find world-writable filesfind / -perm -0002 -type f 2>/dev/nullfind / -perm -0002 -type d 2>/dev/null # world-writable dirs# Check sudo permissionssudo -l # what can current user sudo?# Check cron jobscrontab -l # current user's cronsudo crontab -l # root's cronls -la /etc/cron* # system cron jobscat /etc/crontab# Check running servicessystemctl list-units --type=service --state=running# Check open portsss -tulnp# Check for unpatched packagessudo apt list --upgradable 2>/dev/null | grep -i security
Debian Server Setup
LAMP Stack (Apache + MySQL + PHP)
# ── Apache ────────────────────────────────────────────────────sudo apt install apache2sudo systemctl enable --now apache2# Apache managementsudo a2ensite mysite.conf # enable virtual hostsudo a2dissite 000-default.conf # disable default sitesudo a2enmod rewrite # enable mod_rewritesudo a2enmod ssl # enable SSL modulesudo a2dismod status # disable status modulesudo apache2ctl configtest # test config syntaxsudo systemctl reload apache2 # reload after config changes# ── MySQL / MariaDB ───────────────────────────────────────────sudo apt install mariadb-server mariadb-clientsudo systemctl enable --now mariadbsudo mysql_secure_installation # secure the installation (run this!)# MySQL basicssudo mysql -u root -p # login as rootmysql -u dbuser -p mydb # login as user# Inside MySQL:# CREATE DATABASE myapp;# CREATE USER 'myuser'@'localhost' IDENTIFIED BY 'password';# GRANT ALL PRIVILEGES ON myapp.* TO 'myuser'@'localhost';# FLUSH PRIVILEGES;# SHOW DATABASES;# EXIT;# ── PHP ───────────────────────────────────────────────────────sudo apt install php php-mysql php-cli php-curl php-gd php-mbstring \ php-xml php-zip php-bcmath php-json libapache2-mod-php# Check PHP versionphp -vphp -m # list loaded modules# PHP configsudo nano /etc/php/8.2/apache2/php.ini# Key settings:# upload_max_filesize = 64M# post_max_size = 64M# memory_limit = 256M# max_execution_time = 300sudo systemctl restart apache2
graph LR
EXP["🧪 Experimental\nHighly unstable\npre-upload testing"]
SID["🔴 Unstable (Sid)\nAlways 'sid'\nNew packages land here\nNo freeze ever"]
TEST["🟡 Testing (trixie)\nMigrates from Sid\nafter 10 days + no RC bugs\nFreezes before release"]
STABLE["🟢 Stable (bookworm)\nFrozen, thoroughly tested\nSecurity updates only\n~2 year release cycle"]
OLDSTABLE["📦 Oldstable (bullseye)\nPrevious stable\nLTS security support\n~1 year after new stable"]
ARCHIVE["🗄️ Archive\nEnd of Life\ndeb.debian.org/debian-archive"]
EXP -->|"developer uploads"| SID
SID -->|"10 days + RC bug free"| TEST
TEST -->|"freeze → full release"| STABLE
STABLE -->|"next release"| OLDSTABLE
OLDSTABLE -->|"EOL"| ARCHIVE
When to Use Each Branch
Branch
Stability
Package Age
Use Case
Risk
Stable
★★★★★
1-2 years old
Production servers, critical systems
Very low
Oldstable
★★★★★
2-3 years old
Legacy systems, extended support
Very low
Testing
★★★☆☆
Weeks-months old
Developer workstations, pre-production
Medium
Unstable (Sid)
★★☆☆☆
Days-weeks old
Package development, bleeding edge
High
Experimental
★☆☆☆☆
Hours-days old
Package developers only
Very high
Stable Branch
# /etc/apt/sources.list for Stable (Bookworm)deb http://deb.debian.org/debian bookworm main contrib non-free non-free-firmwaredeb http://security.debian.org/debian-security bookworm-security main contrib non-free non-free-firmwaredeb http://deb.debian.org/debian bookworm-updates main contrib non-free non-free-firmware# Pros: rock-solid, security patches, predictable# Cons: older packages (e.g., PHP 8.2, Python 3.11, Node 18 in bookworm)# Solution for newer packages: use backports or Docker containers
Testing Branch
# /etc/apt/sources.list for Testing (Trixie)deb http://deb.debian.org/debian trixie main contrib non-free non-free-firmwaredeb http://security.debian.org/debian-security trixie-security main contrib non-free non-free-firmwaredeb http://deb.debian.org/debian trixie-updates main contrib non-free non-free-firmware# Pros: newer packages, still reasonably stable# Cons: occasional breakage, especially during freeze transitions# Note: during freeze, Testing gets very stable (good time to use it)
Unstable (Sid)
# /etc/apt/sources.list for Siddeb http://deb.debian.org/debian sid main contrib non-free non-free-firmware# Pros: latest packages, same as what Debian developers use# Cons: can break at any time, no security team support (packages updated directly)# Note: "Sid" = "Still In Development" — named after the destructive kid in Toy Story
Mixing Branches with Pinning
# /etc/apt/sources.list — Stable + Testing mix (use with caution)deb http://deb.debian.org/debian bookworm main contrib non-free non-free-firmwaredeb http://security.debian.org/debian-security bookworm-security maindeb http://deb.debian.org/debian bookworm-updates maindeb http://deb.debian.org/debian trixie main contrib non-free non-free-firmware