Logo

Cheatsheets

Una colección de comandos que vale la pena tener cerca cuando toca construir, mantener o rescatar un sistema.

02 / server ops

Debian

Administración de servidores Debian sin salir de la terminal.

Debian Cheat Sheet

Common commands for Debian Server Administration.


Getting Help

Command / ResourceDescription
man page or man bashRead the help page for every command and many configuration files. Also available online: https://www.manpages.debian.org/
command [--help, -h]Brief help for most commands.
/usr/share/doc/package-name/Find all documentation here; the optional file README.Debian contains Debian-specific notes.
Web documentationReference, manuals, FAQs, HOWTOs, etc.
Mailing listsThe community is always helpful; search for users. Or use other channels like IRC: https://www.debian.org/support/
The WikiContains all kinds of useful information.
⭐ man -k keyword / apropos keywordSearch man pages by keyword.
⭐ info commandRead GNU info documentation.
⭐ whatis commandOne-line description of a command.
⭐ type command / which commandShow how a command resolves / where it lives.
⭐ tldr commandSimplified community examples (needs tldr package).

Installation

ResourceDescription
InstallerAll information about the installer.
CD imagesDownload installation images.
boot: expertE.g. to set up the network without DHCP or to adapt the bootloader installation.
Live imageContains the user-friendly Calamares installer.
⭐ sha256sum -c SHA256SUMSVerify the integrity of a downloaded ISO.
⭐ sudo dd if=debian.iso of=/dev/sdX bs=4M status=progress conv=fsyncWrite an ISO to a USB drive (double-check /dev/sdX!).

Configuration

Command / PathDescription
/etc/All system configuration files are under this directory.
editor filesDefault text editor. May be nano, emacs, vi, joe.
CUPSBrowser interface to the printing system (http://hostname:631).
dpkg-reconfigure package-nameReconfigure a package, e.g. keyboard-configuration (keyboard), locales (localization).
update-alternatives optionsManage command alternatives.
update-grubRun after changing /etc/default/grub.
⭐ sudo update-alternatives --config editorInteractively choose the default editor.
⭐ sudo visudoSafely edit /etc/sudoers.
⭐ sudo timedatectl set-timezone America/SantiagoSet the system time zone.
⭐ timedatectlShow date, time, and NTP sync status.
⭐ sudo hostnamectl set-hostname NAMESet the machine hostname.
⭐ sudo dpkg-reconfigure tzdataReconfigure time zone interactively.
⭐ locale / sudo dpkg-reconfigure localesShow / configure system locales.
⭐ /etc/apt/sources.list and /etc/apt/sources.list.d/APT repository definitions (Trixie also supports deb822 .sources files).
⭐ /etc/fstabFilesystems mounted at boot.
⭐ /etc/hostsStatic hostname-to-IP mappings.

Daemons and System

Command / PathDescription
systemctl restart name.serviceRestart a service / system daemon.
systemctl stop name.serviceStop a service / system daemon.
systemctl start name.serviceStart a service / system daemon.
systemctl haltHalts the system.
systemctl rebootReboots the system.
systemctl poweroffShuts down the system.
systemctl suspendSuspends the system.
systemctl hibernateHibernates the system.
/var/log/All log files are under this directory.
/etc/default/Default values for many daemons and services.
⭐ systemctl status name.serviceShow service status and recent log lines.
⭐ systemctl enable name.serviceStart a service at boot.
⭐ systemctl enable --now name.serviceEnable at boot and start immediately.
⭐ systemctl disable name.serviceDo not start a service at boot.
⭐ systemctl reload name.serviceReload configuration without full restart.
⭐ systemctl is-active name.serviceCheck if a service is running.
⭐ systemctl list-units --type=serviceList loaded services.
⭐ systemctl list-unit-files --state=enabledList services enabled at boot.
⭐ systemctl --failedList failed units.
⭐ systemctl daemon-reloadReload systemd after editing unit files.
⭐ systemctl edit name.serviceCreate a drop-in override for a unit.
⭐ journalctl -u name.service -fFollow logs for a service.
⭐ journalctl -xeShow recent logs with explanations.
⭐ journalctl -bLogs since the current boot.
⭐ journalctl -p err -bOnly errors since boot.
⭐ journalctl --vacuum-time=7dTrim journal logs older than 7 days.
⭐ systemd-analyze blameShow which units slow down boot.
⭐ uptime / uname -a / hostnamectlSystem uptime / kernel info / host info.
⭐ lsb_release -a / cat /etc/os-releaseShow Debian version.
⭐ crontab -e / crontab -lEdit / list the user’s cron jobs.
⭐ systemctl list-timersList systemd timers.

Important Shell Commands

Files and directories

CommandDescription
cat filesPrint files to screen.
cd directoryChange to directory.
cp files destCopy files and directories.
echo stringEcho string to screen.
gzip, bzip2, xz [-d] filesCompress, uncompress files.
pager filesShow contents of files.
ls [files]List files.
mkdir directory-namesCreate directories.
mv file1 file2Move, rename files.
rm filesRemove files.
rmdir dirsRemove empty directories.
tar [c][x][t][z][j][J] -f file.tar [files]Create (c), extract (x), list table of (t) archive file; z for .gz, j for .bz2, J for .xz.
find directories expressionsFind files, like -name name or -size +1000, etc.
grep search-string filesFind search-string in files.
ln -s file linkCreate a symbolic link to a file.

Processes and users

CommandDescription
ps [options]Show current processes.
kill [-9] PIDSend signal to a process (e.g. terminate it). Use ps for the PID.
su - [username]Become another user, e.g. root.
sudo commandExecute a command as root as a normal user, see /etc/sudoers.

Redirection and pipes

CommandDescription
command > fileOverwrite file with output of command.
command >> fileAppend output of command to file.
cmd1 | cmd2Use output of command 1 as input of command 2.
command < fileUse file as input for command.

⭐ Additional shell commands

CommandDescription
ls -lahLong listing, hidden files, human-readable sizes.
tree -L 2Directory tree, 2 levels deep (needs tree).
cp -a src destCopy preserving permissions, timestamps, links.
rm -rf dirRemove a directory recursively (dangerous, no undo).
touch fileCreate an empty file / update timestamp.
head -n 20 file / tail -n 20 fileFirst / last lines of a file.
tail -f fileFollow a file as it grows (logs).
less fileScroll through a file (q to quit, / to search).
wc -l fileCount lines.
sort file | uniq -cSort and count duplicates.
cut -d: -f1 /etc/passwdExtract a column by delimiter.
sed -i 's/old/new/g' fileIn-place search and replace.
awk '{print $1}' filePrint first column.
grep -rin "text" .Recursive, case-insensitive search with line numbers.
find . -name "*.log" -mtime +7Find .log files older than 7 days.
find . -type f -size +100MFind files larger than 100 MB.
xargsBuild commands from stdin, e.g. find . -name "*.tmp" | xargs rm.
tar -czvf out.tar.gz dir/Create a gzip-compressed archive.
tar -xzvf in.tar.gz -C /destExtract a gzip archive to a destination.
zip -r out.zip dir/ / unzip file.zipCreate / extract zip files.
chmod 755 file / chmod +x script.shChange permissions.
chown user:group fileChange owner and group.
chown -R user:group dirChange ownership recursively.
umaskShow default permission mask.
stat fileDetailed file information.
file nameDetect file type.
diff -u a bCompare two files.
alias ll='ls -lah'Create a shell alias (persist in ~/.bashrc).
history / Ctrl+RCommand history / reverse search.
!!Repeat last command (e.g. sudo !!).
source ~/.bashrcReload shell configuration.
export VAR=valueSet an environment variable.
env / printenvList environment variables.
watch -n 2 commandRe-run a command every 2 seconds.
time commandMeasure how long a command takes.
tmux / screenPersistent terminal sessions (need packages).

⭐ Users and groups

CommandDescription
whoami / idCurrent user / UID, GID, and groups.
sudo adduser nameCreate a user (interactive, Debian-friendly).
sudo usermod -aG sudo nameAdd a user to the sudo group.
sudo deluser --remove-home nameDelete a user and their home directory.
sudo passwd nameChange a user’s password.
groups nameShow a user’s groups.
lastShow recent logins.
w / whoWho is logged in and what they are doing.

⭐ Processes and resources

CommandDescription
top / htopInteractive process viewer (htop needs package).
ps auxList all processes.
ps aux | grep nameFind a process by name.
pgrep -a nameFind PIDs by name.
pkill nameKill processes by name.
killall nameKill all processes with that name.
nice -n 10 cmd / renice -n 5 -p PIDStart with / change priority.
bg / fg / jobsManage background jobs.
command &Run a command in background.
nohup command &Keep running after logout.
free -hMemory usage.
vmstat 1Live virtual memory/CPU stats.
lsof -i :80Which process uses port 80.
dmesg -T | tailRecent kernel messages with human-readable time.

⭐ Disk and filesystems

CommandDescription
df -hFree disk space per filesystem.
du -sh *Size of each item in the current directory.
du -h --max-depth=1 / | sort -hLargest top-level directories.
ncduInteractive disk usage browser (needs package).
lsblkList block devices.
lsblk -fList block devices with filesystems and UUIDs.
blkidShow UUIDs and filesystem types.
sudo fdisk -lList disk partitions.
sudo mount /dev/sdX1 /mnt / sudo umount /mntMount / unmount a partition.
sudo mount -aMount everything in /etc/fstab (test your edits).
sudo fsck /dev/sdX1Check a filesystem (unmounted!).
sudo mkfs.ext4 /dev/sdX1Format as ext4 (destroys data).
sudo smartctl -a /dev/sdaDisk SMART health (needs smartmontools).

⭐ Hardware info

CommandDescription
lscpuCPU information.
lspci / lsusbPCI / USB devices.
sudo lshw -shortHardware summary.
sudo dmidecode -t systemBIOS/system information.
sensorsTemperatures (needs lm-sensors).
nvidia-smiNVIDIA GPU status (with proprietary drivers).

APT

CommandDescription
apt updateUpdate package listings from repositories listed in /etc/apt/sources.list. Required whenever that file or the contents of the repositories change.
apt search search-stringSearch packages and descriptions for the string.
apt list -a package-nameShow versions and archive areas of available packages.
apt show -a package-nameShow package information including description.
apt install package-namesInstall packages from repositories with all dependencies.
apt upgradeInstall newest versions of all packages currently installed.
apt full-upgradeLike apt upgrade, but with advanced conflict resolution.
apt remove package-namesRemove packages.
apt autoremoveRemove packages that no other packages depend on.
apt depends package-nameList all packages needed by the one given.
apt rdepends package-nameList all packages that need the one given.
apt-file updateUpdate content listings from package repositories, see apt update.
apt-file search file-nameSearch packages for a file.
apt-file list package-nameList contents of a package.
aptitudeConsole interface to APT (needs aptitude).
synapticGUI interface to APT (needs synaptic).

⭐ Additional APT commands

CommandDescription
sudo apt update && sudo apt upgrade -yTypical full refresh and upgrade.
sudo apt full-upgradeUpgrade handling changed dependencies.
sudo apt purge packageRemove a package and its configuration files.
sudo apt autoremove --purgeRemove unused packages and their configs.
sudo apt cleanDelete all cached .deb files.
sudo apt autocleanDelete only obsolete cached .deb files.
sudo apt install ./file.debInstall a local .deb resolving dependencies.
sudo apt install --reinstall packageReinstall a package.
sudo apt install package=versionInstall a specific version.
sudo apt install -t trixie-backports packageInstall from backports.
sudo apt --fix-broken installRepair broken dependencies.
apt list --installedList installed packages.
apt list --upgradableList packages with updates available.
apt policy packageShow candidate version and pinning/priorities.
apt-mark hold package / apt-mark unhold packagePrevent / allow upgrades of a package.
apt-mark showholdList held packages.
apt-mark showmanualList manually installed packages.
sudo apt build-dep packageInstall build dependencies (needs deb-src).
apt source packageDownload package source.
sudo apt modernize-sourcesConvert legacy sources.list to deb822 format.
sudo apt-get dist-upgradeLegacy equivalent of full-upgrade.
needrestartShow services/processes needing restart after upgrades (needs package).
sudo unattended-upgrades --dry-runTest automatic security upgrades (needs unattended-upgrades).
sudo add-apt-repositoryNot shipped by default on Debian; edit /etc/apt/sources.list.d/ instead.

⭐ Third-party repository (modern way, with keyrings)

sudo install -d -m 0755 /etc/apt/keyrings
curl -fsSL https://example.com/key.gpg | sudo gpg --dearmor -o /etc/apt/keyrings/example.gpg
echo "deb [signed-by=/etc/apt/keyrings/example.gpg] https://example.com/apt stable main" \
  | sudo tee /etc/apt/sources.list.d/example.list
sudo apt update

Dpkg

CommandDescription
dpkg -l [names]List packages.
dpkg -I pkg.debShow package information.
dpkg -c pkg.debList contents of a package file.
dpkg -S filenameShow which package a file belongs to.
dpkg -i pkg.debInstall package files.
dpkg -V [package-names]Audit checksums of installed packages.
dpkg-divert [options] fileOverride a package’s version of a file.
dpkg --compare-versions v1 gt v2Compare version numbers; view results with echo $?.
dpkg-query -W --showformat=formatQuery installed packages, format e.g. '${Package} ${Version} ${Installed-Size}\n'
dpkg --get-selections > fileWrite package selections to file.
dpkg --set-selections < fileSet package selections from file.

⭐ Additional dpkg commands

CommandDescription
dpkg -L packageList files installed by a package.
dpkg -s packageShow status of an installed package.
dpkg -r packageRemove a package (keep config).
dpkg -P packagePurge a package (remove config too).
sudo dpkg --configure -aFinish configuring interrupted installations.
dpkg --print-architectureShow the native architecture.
dpkg --print-foreign-architecturesShow enabled foreign architectures.
sudo dpkg --add-architecture i386Enable multiarch (e.g. i386).
dpkg -l | grep ^iiOnly fully installed packages.
dpkg -l | grep ^rcRemoved packages with leftover config.
sudo dpkg -P $(dpkg -l | awk '/^rc/{print $2}')Purge leftover configs of removed packages.

The Network

Command / PathDescription
/etc/network/interfacesInterface configuration (if not controlled via NetworkManager).
if[up][down] deviceStart, stop network interfaces according to the file above.
ipShow and manipulate network interfaces and routing (needs iproute2).
ssh -X user@hostLogin at another machine (with X11 forwarding).
scp files user@host:pathCopy files to another machine (and vice versa).

⭐ Additional networking commands

CommandDescription
ip a / ip addrShow IP addresses.
ip -br aBrief address overview.
ip linkShow network interfaces and state.
sudo ip link set eth0 up / downBring an interface up / down.
ip routeShow routing table.
ip route get 1.1.1.1Show which route/interface reaches a host.
ss -tulpnListening TCP/UDP sockets with owning processes.
ss -tnEstablished TCP connections.
ping -c 4 hostTest connectivity.
traceroute host / mtr hostTrace the route to a host (need packages).
dig domain / nslookup domainDNS lookups (need dnsutils/bind9-dnsutils).
dig +short domainOnly the answer.
host domainSimple DNS lookup.
resolvectl statusDNS resolver status (systemd-resolved).
curl -I https://example.comFetch HTTP headers only.
curl -fsSL URL -o fileDownload a file quietly, failing on errors.
wget URL / wget -c URLDownload / resume download.
nmcli device statusNetworkManager device status.
nmcli connection showList NetworkManager connections.
nmcli device wifi list / nmcli device wifi connect SSID password PASSList / connect to Wi-Fi.
nmtuiText UI for NetworkManager.
sudo systemctl restart networkingRestart ifupdown networking.
sudo systemctl restart NetworkManagerRestart NetworkManager.
hostname -IShow all local IP addresses.
curl ifconfig.meShow public IP address.
nc -zv host 22Test whether a TCP port is open (needs netcat).
nmap hostPort scan (needs nmap; only scan hosts you own/are authorized to).
sudo tcpdump -i eth0 port 80Capture packets (needs tcpdump).

⭐ SSH and file transfer

CommandDescription
ssh user@hostConnect to a remote machine.
ssh -p 2222 user@hostConnect using a non-default port.
ssh -i ~/.ssh/key user@hostConnect with a specific key.
ssh-keygen -t ed25519 -C "comment"Generate an Ed25519 key pair.
ssh-copy-id user@hostInstall your public key on a remote host.
ssh -L 8080:localhost:80 user@hostLocal port forwarding (tunnel).
ssh -D 1080 user@hostSOCKS proxy through SSH.
ssh -J jump@host user@targetConnect through a jump host.
scp -r dir user@host:/pathCopy a directory recursively.
scp -P 2222 file user@host:/pathCopy using a non-default port.
rsync -avzP src/ user@host:/dest/Efficient sync with progress and resume.
rsync -avz --delete src/ dest/Mirror, deleting extra files at the destination.
sftp user@hostInteractive file transfer.
~/.ssh/configPer-host SSH settings (Host, HostName, User, Port, IdentityFile).

⭐ Firewall

CommandDescription
sudo ufw status verboseShow firewall status (needs ufw).
sudo ufw allow 22/tcpAllow SSH.
sudo ufw allow from 192.168.1.0/24 to any port 5432Allow a subnet to a port.
sudo ufw allow from 192.168.1.0 to any port 5432Allow a specific ip to a port.
sudo ufw allow from 192.168.1.0 to any port 5432 proto tcpAllow a specific ip to a port with only tcp protocol.
sudo ufw deny 23Block a port.
sudo ufw enable / disableEnable / disable the firewall.
sudo ufw delete allow 22/tcpRemove a rule.
sudo nft list rulesetShow nftables rules (Debian default backend).
sudo systemctl status fail2banCheck brute-force protection (needs fail2ban).

Kernel and boot

CommandDescription
uname -rRunning kernel version.
dpkg -l 'linux-image*' | grep ^iiInstalled kernels.
sudo update-initramfs -uRebuild the initramfs.
sudo update-grubRegenerate GRUB configuration.
lsmodLoaded kernel modules.
sudo modprobe moduleLoad a kernel module.
sudo sysctl -a | grep keywordSearch kernel parameters.
sudo sysctl -pReload /etc/sysctl.conf.

Upgrading Debian to a new release (e.g. 12 → 13)

# 1. Fully update the current system first
sudo apt update && sudo apt full-upgrade
# 2. Back up, then change codenames in /etc/apt/sources.list(.d/)
sudo sed -i 's/bookworm/trixie/g' /etc/apt/sources.list
# 3. Upgrade in two steps
sudo apt update
sudo apt upgrade --without-new-pkgs
sudo apt full-upgrade
# 4. Clean up and reboot
sudo apt autoremove --purge
sudo reboot

Always read the official release notes before a major upgrade: https://www.debian.org/releases/stable/releasenotes

Handy one-liners

# Show the 10 biggest files/directories under the current path
du -ah . 2>/dev/null | sort -rh | head -n 10

# Show the 10 processes using the most memory
ps aux --sort=-%mem | head -n 11

# Find which process is using a port
sudo ss -tulpn | grep :8080

# Count files in a directory recursively
find . -type f | wc -l

# Update everything and clean up in one go
sudo apt update && sudo apt full-upgrade -y && sudo apt autoremove --purge -y && sudo apt clean