Linux: Complete Visual Guide

From first command to production administration, everything simplified

7 Fundamentals
7 System
7 Network & Security

1. What is Linux

🐧 What is Linux

KernelCreated by Linus Torvalds in 1991, the core of the OS LicenseOpen source, GNU General Public License (GPL) Multi-userMultiple users can work simultaneously Multi-taskingRun thousands of processes concurrently Runs EverywhereServers, cloud, IoT, phones (Android), supercomputers Server Share96%+ of the top 1 million web servers run Linux Supercomputers100% of the top 500 supercomputers run Linux Philosophy"Everything is a file", devices, processes, sockets are files

πŸ—οΈ Linux Architecture

Applications / User Space Browsers, editors, scripts, containers
Shell bash, zsh, fish, command interpreter
System Libraries glibc, bridge between apps and kernel
Kernel Process, memory, device, file system management
Hardware CPU, RAM, disk, NIC, GPU

☁️ Why Linux for Cloud & DevOps

Cloud VMsEvery major cloud (AWS, GCP, Azure) runs Linux by default ContainersDocker and all containers are built on Linux kernel features KubernetesAll K8s nodes run Linux, control plane and workers DevOps ToolsTerraform, Ansible, Jenkins, all Linux-native CI/CDGitHub Actions, GitLab CI, runners are Linux CostFree, no licensing fees, massive community support
2. Linux Distributions

πŸ“¦ Major Linux Distributions

DistroBasePkg ManagerUse Case
UbuntuDebianaptGeneral purpose, cloud VMs, most popular
DebianIndependentaptServers, stability-focused
RHELIndependentyum / dnfEnterprise production, paid support
CentOS / RockyRHELyum / dnfEnterprise (free RHEL alternative)
FedoraRHEL upstreamdnfCutting-edge features, developer desktop
AlpineIndependentapkContainers, minimal ~5MB base image
Amazon LinuxRHELyumAWS-optimized instances
SUSE / openSUSEIndependentzypperEnterprise (SAP, Europe)
ArchIndependentpacmanRolling release, advanced users

βš”οΈ Debian Family vs RHEL Family

πŸ”΅ Debian / Ubuntu

  • Package: .deb
  • Manager: apt / dpkg
  • Config: /etc/apt/
  • Popular for cloud VMs
  • Huge community
vs

πŸ”΄ RHEL / CentOS / Rocky

  • Package: .rpm
  • Manager: yum / dnf
  • Config: /etc/yum.repos.d/
  • Enterprise standard
  • Paid support available

🎯 How to Choose a Distro

Cloud VMsUbuntu or Debian, most cloud-friendly EnterpriseRHEL or Rocky Linux, certified, supported ContainersAlpine, tiny footprint, fast builds DesktopUbuntu or Fedora, best hardware support AWS WorkloadsAmazon Linux, kernel tuned for EC2 LearningUbuntu, largest community, most tutorials
3. File System Hierarchy

πŸ—‚οΈ FHS, Filesystem Hierarchy Standard

/ (root)
/bin, Essential user commands (ls, cp, mv)
/sbin, System admin binaries (fdisk, mount)
/etc, Configuration files (all system configs)
/home, User home directories (/home/alice)
/var, Variable data (logs, spool, cache)
/tmp, Temporary files (cleared on reboot)
/usr, User programs and data (/usr/bin, /usr/lib)
/opt, Third-party software packages
/dev, Device files (/dev/sda, /dev/null)
/proc, Virtual FS, process and kernel info
/sys, Virtual FS, hardware and driver info
/boot, Bootloader, kernel, initramfs
/lib, Shared libraries for /bin and /sbin
/mnt, Temporary mount point for filesystems
/media, Removable media (USB, CD-ROM)
/srv, Service data (web, FTP)
/root, Root user's home directory
/run, Runtime data since last boot

πŸ“ Key Directories

/etcAll system configuration files /var/logLog files (syslog, auth, kern) /homeUser home directories /tmpTemporary files (world-writable) /usr/binUser-installed programs /usr/localLocally compiled software /optThird-party applications /procLive process and system info /devDevice files (/dev/null, /dev/zero)

πŸ“„ File Types in Linux

SymbolTypeExample
-Regular file/etc/passwd
dDirectory/home/alice
lSymbolic link/usr/bin/python β†’ python3
bBlock device/dev/sda
cCharacter device/dev/tty
pNamed pipe (FIFO)mkfifo mypipe
sSocket/var/run/docker.sock

Use ls -l, first character shows the type

4. Essential Commands

⌨️ Navigation & File Commands

CommandDescriptionExample
pwdPrint working directorypwd β†’ /home/alice
lsList directory contentsls -la (all + details)
cdChange directorycd /var/log, cd .., cd ~
mkdirCreate directorymkdir -p dir/sub/deep
rmdirRemove empty directoryrmdir olddir
touchCreate file / update timestamptouch newfile.txt
cpCopy files/directoriescp -r src/ dest/
mvMove or renamemv old.txt new.txt
rmRemove files/directoriesrm -rf dir/ (caution!)
findSearch for filesfind / -name "*.log"
locateFast file search (indexed)locate nginx.conf
whichShow command pathwhich python3
fileIdentify file typefile image.png
statDetailed file infostat /etc/passwd
treeDirectory tree viewtree -L 2
lnCreate linksln -s target link (symlink)
realpathResolve full pathrealpath ./script.sh

πŸ“– File Content Commands

CommandDescriptionExample
catDisplay entire filecat /etc/hostname
lessPaginated viewer (scroll)less /var/log/syslog
headFirst N lineshead -20 file.txt
tailLast N lines / followtail -f /var/log/syslog
wcCount lines, words, byteswc -l file.txt
sortSort linessort -n numbers.txt
uniqRemove adjacent duplicatessort file | uniq -c
diffCompare two filesdiff file1 file2
teeRead stdin, write to file + stdoutecho hi | tee out.txt
cutExtract columnscut -d: -f1 /etc/passwd
trTranslate / delete charactersecho HELLO | tr A-Z a-z

πŸ”€ Wildcards & Redirection

PatternMeaning
*Match any characters (zero or more)
?Match exactly one character
[abc]Match one of the listed characters
[0-9]Match a range of characters
OperatorFunction
>Redirect stdout (overwrite)
>>Redirect stdout (append)
<Redirect stdin (input)
2>Redirect stderr
&>Redirect both stdout + stderr
|Pipe, send output to next command

πŸ• Aliases & History

alias ll='ls -la'Create a shortcut unalias llRemove the alias historyShow command history !!Repeat last command !42Run history command #42 Ctrl+RReverse search through history Ctrl+CCancel current command Ctrl+LClear screen Ctrl+A / Ctrl+EJump to start / end of line

Aliases go in ~/.bashrc or ~/.zshrc for persistence

5. File Permissions

πŸ” Permission Model

Every file has 3 permission groups:

GroupSymbolApplies to
OwneruThe file's creator
GroupgUsers in the file's group
OthersoEveryone else

Each group has 3 permissions:

PermissionSymbolNumericFileDirectory
Readr4View contentsList files
Writew2ModifyCreate/delete files
Executex1Run as programEnter (cd into)

Example: rwxr-xr-- = 754

Owner
rwx
4+2+1 = 7
Group
r-x
4+0+1 = 5
Others
r--
4+0+0 = 4

-rwxr-xr-- 1 alice devs 4096 file.txt
│└─Ownerβ”€β”˜β””Groupβ”˜β””Othersβ”˜

πŸ› οΈ Permission Commands

CommandDescriptionExample
chmodChange modechmod 755 script.sh
chmodSymbolic modechmod u+x,g-w file
chownChange ownerchown alice:devs file
chgrpChange groupchgrp devs file
umaskDefault permission maskumask 022 β†’ new files get 644

Symbolic: u (user), g (group), o (others), a (all). + add, - remove, = set exact

⚑ Special Permissions

PermissionNumericSymbolEffect
SUID4000s on owner xRun as file owner (e.g. /usr/bin/passwd)
SGID2000s on group xNew files inherit group / run as group
Sticky Bit1000t on others xOnly owner can delete files (e.g. /tmp)
/tmpdrwxrwxrwt, sticky bit set, anyone writes but only owners delete /usr/bin/passwd-rwsr-xr-x, SUID set, runs as root to update /etc/shadow

πŸ“‹ Common Permission Patterns

NumericSymbolicUse Case
755rwxr-xr-xExecutables and public directories
644rw-r--r--Regular files (config, text)
600rw-------Private files (SSH keys, secrets)
700rwx------Private directories, ~/.ssh
444r--r--r--Read-only for everyone
777rwxrwxrwxAVOID, full access to everyone
6. Users & Groups

πŸ‘₯ User Management Commands

CommandDescriptionExample
useraddCreate useruseradd -m -s /bin/bash alice
usermodModify userusermod -aG docker alice
userdelDelete useruserdel -r alice (with home dir)
passwdSet passwordpasswd alice
groupaddCreate groupgroupadd devops
groupdelDelete groupgroupdel devops
idShow user/group IDsid alice
whoamiCurrent usernamewhoami β†’ alice
who / wWho is logged inw (detailed view)
lastLogin historylast -10
suSwitch usersu - alice
sudoRun as superusersudo apt update

πŸ“‚ Key User Files

/etc/passwdUser accounts, name:x:UID:GID:info:home:shell /etc/shadowEncrypted passwords (root-only) /etc/groupGroup definitions, name:x:GID:members /etc/sudoersSudo access rules (edit with visudo) /etc/login.defsPassword aging and UID ranges /etc/skelTemplate for new user home directories

πŸ†” User Types

TypeUID RangePurpose
Root0Superuser, full system access
System1–999Services (www-data, mysql, nobody)
Regular1000+Human users (alice, bob)

Check with: id username, shows UID, GID, and groups

πŸ›‘οΈ sudo, Superuser Do

What is sudoRun a single command as root without switching users sudo commandExecute command as root sudo -u alice cmdRun as a specific user visudoSafe editor for /etc/sudoers NOPASSWDalice ALL=(ALL) NOPASSWD: ALL sudo vs susudo = one command, su = switch entire session Best practiceNever log in as root, always use sudo
7. Text Editors

πŸ“ Vim Essentials

ModeKeyAction
Normal β†’ InsertiInsert before cursor
Normal β†’ InsertaAppend after cursor
Normal β†’ InsertoOpen new line below
Any β†’ NormalEscReturn to normal mode
NormalddDelete (cut) entire line
NormalyyYank (copy) line
NormalpPaste after cursor
NormaluUndo
Normal/patternSearch forward
Normaln / NNext / previous match
Command:wSave file
Command:qQuit
Command:wqSave and quit
Command:q!Quit without saving
Command:%s/old/new/gFind and replace all

Modes: Normal (navigate) β†’ Insert (type) β†’ Visual (select) β†’ Command (:)

✏️ Nano Essentials

ShortcutAction
Ctrl+OSave (Write Out)
Ctrl+XExit nano
Ctrl+KCut current line
Ctrl+UPaste (Uncut)
Ctrl+WSearch text
Ctrl+\\Find and replace
Ctrl+GHelp
Ctrl+_Go to line number
Alt+UUndo

Nano shows shortcuts at the bottom, ^ means Ctrl

βš–οΈ Vim vs Nano

⚑ Vim

  • Steep learning curve
  • Extremely powerful once mastered
  • Modal editing (modes)
  • Available on every Linux
  • Plugins, syntax highlighting
  • Best for power users
vs

πŸ“ Nano

  • Easy to learn (2 minutes)
  • What-you-see-is-what-you-get
  • Shortcuts shown on screen
  • Available on most systems
  • No modes, just type
  • Best for quick edits

8. Package Management

πŸ“¦ APT vs YUM / DNF

TaskAPT (Debian/Ubuntu)YUM/DNF (RHEL/CentOS)
Install packageapt install nginxdnf install nginx
Remove packageapt remove nginxdnf remove nginx
Update package listapt updatednf check-update
Upgrade allapt upgradednf upgrade
Searchapt search nginxdnf search nginx
List installedapt list --installeddnf list installed
Show infoapt show nginxdnf info nginx
Clean cacheapt cleandnf clean all
Auto-remove unusedapt autoremovednf autoremove

πŸ”„ Package Lifecycle

Repository
β†’
Download
β†’
Dependency Resolution
β†’
Install
β†’
Configure
β†’
Update / Remove

Repositories defined in /etc/apt/sources.list (Debian) or /etc/yum.repos.d/ (RHEL)

🧩 Other Package Tools

snapUniversal packages (Canonical), snap install code flatpakUniversal packages (Fedora), desktop apps pipPython packages, pip install flask npmNode.js packages, npm install express gemRuby packages, gem install rails From source./configure β†’ make β†’ make install

Prefer system packages (apt/dnf) over compiling from source when possible

9. Process Management

βš™οΈ Process Commands

CommandDescriptionExample
psList processesps aux (all processes, detailed)
topLive process monitortop (q to quit)
htopBetter top (interactive)htop (install if missing)
killSend signal to processkill -15 1234 (graceful)
kill -9Force killkill -9 1234 (last resort)
killallKill by namekillall nginx
pkillKill by patternpkill -f "python app"
niceStart with prioritynice -n 10 command
reniceChange running priorityrenice -5 -p 1234
nohupSurvive logoutnohup script.sh &
bg / fgBackground / foregroundCtrl+Z then bg
jobsList background jobsjobs -l
&Run in background./script.sh &
pgrepFind PID by namepgrep nginx

πŸ”„ Process States

Created (fork/exec)
Ready (waiting for CPU)
Running (executing on CPU)
Sleeping (S)
Waiting for I/O
Stopped (T)
Ctrl+Z / signal
Zombie (Z)
Exited, not reaped
Terminated (exit code returned)

πŸ“‘ Signals

SignalNumberShortcutEffect
SIGHUP1,Hangup, reload config
SIGINT2Ctrl+CInterrupt, graceful stop
SIGQUIT3Ctrl+\\Quit, core dump
SIGKILL9,Force kill, cannot be caught
SIGTERM15,Terminate, graceful (default)
SIGSTOP19Ctrl+ZPause process
SIGCONT18,Resume paused process

Always try kill -15 (SIGTERM) before kill -9 (SIGKILL)

πŸ“Š /proc Filesystem

/proc/PID/statusProcess name, state, memory, threads /proc/PID/cmdlineCommand that started the process /proc/PID/fd/Open file descriptors /proc/cpuinfoCPU model, cores, speed /proc/meminfoTotal / free / available memory /proc/loadavgSystem load (1, 5, 15 minute avg) /proc/uptimeSeconds since boot /proc/versionKernel version string

/proc is a virtual filesystem, files are generated on the fly by the kernel

10. Systemd & Services

πŸŽ›οΈ systemctl Commands

CommandDescription
systemctl start nginxStart service now
systemctl stop nginxStop service now
systemctl restart nginxStop then start
systemctl reload nginxReload config without downtime
systemctl enable nginxStart on boot
systemctl disable nginxDon't start on boot
systemctl status nginxShow current status and recent logs
systemctl is-active nginxCheck if running (returns active/inactive)
systemctl is-enabled nginxCheck if enabled at boot
systemctl list-units --type=serviceList all loaded services
systemctl daemon-reloadReload unit files after changes
systemctl mask nginxPrevent starting (even manually)
systemctl unmask nginxAllow starting again

πŸ“„ Unit File Structure

[Unit]Metadata and dependencies Description=Human-readable name of the service After=Start after these units (e.g. network.target) Requires=Hard dependency, fail if missing [Service]How to run the service ExecStart=Command to start the service Restart=always / on-failure / no User=Run as this user WorkingDirectory=Working directory for the process [Install]How to enable the service WantedBy=Target that pulls in this unit (multi-user.target)

Unit files live in /etc/systemd/system/ (custom) or /lib/systemd/system/ (packages)

πŸš€ Linux Boot Process

BIOS / UEFI
β†’
GRUB Bootloader
β†’
Kernel
β†’
systemd (PID 1)
β†’
Targets
β†’
Services

systemd replaced SysVinit, it is PID 1, the first process, parent of all others

🎯 Targets & Logging

TargetEquivalentPurpose
multi-user.targetRunlevel 3CLI multi-user (servers)
graphical.targetRunlevel 5GUI desktop
rescue.targetRunlevel 1Single-user, minimal repair
emergency.target,Root shell only, no services
journalctlView systemd logs journalctl -u nginxLogs for a specific service journalctl -fFollow live (like tail -f) journalctl --since "1 hour ago"Time-filtered logs
11. Disk & Storage

πŸ’Ύ Disk Commands

CommandDescriptionExample
dfDisk space (filesystem level)df -h (human-readable)
duDirectory disk usagedu -sh /var/log
lsblkList block deviceslsblk -f (with filesystem)
fdiskPartition managerfdisk -l /dev/sda
partedAdvanced partitioningparted /dev/sda print
mkfsCreate filesystemmkfs.ext4 /dev/sdb1
mountAttach filesystemmount /dev/sdb1 /mnt/data
umountDetach filesystemumount /mnt/data
blkidShow block device UUIDsblkid /dev/sda1
freeMemory usage (RAM + swap)free -h
swaponEnable swapswapon /swapfile

πŸ“€ Filesystem Types

ext4Default Linux FS, journaling, stable, up to 1 EB xfsRHEL default, fast, good for large files btrfsAdvanced, snapshots, compression, RAID tmpfsRAM-based FS, /tmp, /run (fast, volatile) swapVirtual memory on disk (when RAM is full) vfatFAT32, USB drives, EFI partition nfsNetwork File System, shared over network

🧱 LVM, Logical Volume Manager

Physical Volume (PV)
β†’
Volume Group (VG)
β†’
Logical Volume (LV)
β†’
Filesystem
pvcreateInitialize physical volume vgcreateCreate volume group from PVs lvcreateCreate logical volume from VG lvextendGrow a logical volume (online resize) AdvantagesResize volumes, snapshots, span multiple disks

πŸ“‹ /etc/fstab, Auto-Mount

FieldDescriptionExample
DeviceUUID or /dev pathUUID=xxxx-xxxx
Mount PointWhere to mount/mnt/data
FS TypeFilesystemext4
OptionsMount optionsdefaults,noatime
DumpBackup flag0 (skip)
Passfsck order2 (check after root)

Always use UUID= instead of /dev/sdX, device names can change on reboot

12. Logs & Journald

πŸ“‹ Important Log Files

/var/log/syslogGeneral system log (Debian/Ubuntu) /var/log/messagesGeneral system log (RHEL/CentOS) /var/log/auth.logAuthentication events (login, sudo, SSH) /var/log/kern.logKernel messages /var/log/dmesgBoot and hardware messages /var/log/apt/Package manager log (Debian) /var/log/yum.logPackage manager log (RHEL) /var/log/nginx/Nginx access and error logs /var/log/cronCron job execution log

πŸ” journalctl, Systemd Logs

CommandDescription
journalctlAll logs (oldest first)
journalctl -u nginxLogs for specific unit
journalctl -fFollow live logs (tail -f style)
journalctl --since "1h ago"Since a time
journalctl --until "2024-01-01"Until a date
journalctl -p errOnly errors and above
journalctl -bLogs from current boot
journalctl -b -1Logs from previous boot
journalctl --no-pagerOutput without paging
journalctl --disk-usageCheck journal disk usage

πŸ”„ Log Rotation

logrotateRotates, compresses, and manages log files Config/etc/logrotate.conf (global), /etc/logrotate.d/ (per-app) rotate NKeep N rotated copies daily/weekly/monthlyRotation frequency compressGzip old logs to save space maxsize 100MRotate when file exceeds size missingokDon't error if log file is missing notifemptyDon't rotate if file is empty

logrotate runs daily via cron (/etc/cron.daily/logrotate)

13. Cron & Scheduling

⏰ Crontab Format

Minute
0–59
Hour
0–23
Day
1–31
Month
1–12
Weekday
0–7
Command
/path/to/script.sh
*Every value (every minute, every hour, etc.) */5Every 5th value (every 5 minutes) 1,15Specific values (1st and 15th) 1-5Range (Monday through Friday, if weekday field)

πŸ“… Common Cron Patterns

ScheduleCrontab
Every minute* * * * * command
Every 5 minutes*/5 * * * * command
Every hour0 * * * * command
Every day at midnight0 0 * * * command
Every Sunday midnight0 0 * * 0 command
First of every month0 0 1 * * command
Weekdays at 9 AM0 9 * * 1-5 command
Every 30 min, 9-5*/30 9-17 * * * command

πŸ› οΈ Cron Tools & Alternatives

crontab -eEdit current user's crontab crontab -lList current user's crontab crontab -rRemove current user's crontab /etc/crontabSystem-wide crontab (has user field) /etc/cron.d/Drop-in cron files /etc/cron.daily/Scripts run daily by anacron /etc/cron.hourly/Scripts run every hour atRun command once at a specific time (at 5pm) systemd timersModern alternative, more features, journald logging
14. Environment Variables

🌍 Key Environment Variables

PATHDirectories searched for commands (/usr/bin:/usr/local/bin:...) HOMECurrent user's home directory (/home/alice) USERCurrent username SHELLDefault shell (/bin/bash, /bin/zsh) LANGSystem locale (en_US.UTF-8) EDITORDefault text editor (vim, nano) TERMTerminal type (xterm-256color) PS1Shell prompt format string HISTSIZENumber of history entries to keep LD_LIBRARY_PATHExtra shared library search paths

βš™οΈ Working with Variables

CommandDescription
export VAR=valueSet and export to child processes
echo $VARPrint variable value
envShow all environment variables
printenv VARPrint specific variable
setShow all shell variables (env + local)
unset VARRemove a variable
~/.bashrcLoaded for interactive non-login shells ~/.bash_profileLoaded for login shells ~/.profileLoaded if no .bash_profile /etc/environmentSystem-wide variables (all users) /etc/profile.d/*.shSystem-wide login scripts

πŸ”„ Shell Config Load Order

Login shell (SSH, console login):

/etc/profile
β†’
~/.bash_profile
β†’
~/.bashrc
β†’
~/.bash_logout

Non-login shell (new terminal tab):

~/.bashrc only

Tip: Put exports in ~/.bashrc and source it from ~/.bash_profile for consistency


15. Linux Networking

🌐 Network Commands

CommandDescriptionExample
ip addrShow IP addresses and interfacesip addr show eth0
ip routeShow routing tableip route show
ip linkManage network interfacesip link set eth0 up
ssSocket statistics (connections)ss -tlnp (TCP listening)
pingTest connectivity (ICMP)ping -c 4 google.com
tracerouteTrace packet pathtraceroute google.com
digDNS lookup (detailed)dig google.com A
nslookupDNS lookup (simple)nslookup google.com
curlTransfer data (HTTP, etc.)curl -I https://example.com
wgetDownload fileswget https://example.com/file.tar.gz
nc (netcat)TCP/UDP swiss-army knifenc -zv host 80 (port check)
hostnameShow or set hostnamehostnamectl set-hostname web01
nmcliNetworkManager CLInmcli device status

πŸ“‚ Network Config Files

/etc/hostsStatic hostname to IP mapping (local DNS override) /etc/resolv.confDNS server addresses (nameserver 8.8.8.8) /etc/hostnameSystem hostname /etc/nsswitch.confName resolution order (files, dns) /etc/network/interfacesNetwork config (Debian, older) /etc/sysconfig/network-scripts/Network config (RHEL/CentOS) /etc/netplan/*.yamlNetwork config (Ubuntu 18.04+)

πŸ”„ Modern vs Legacy Commands

Legacy (deprecated)Modern Replacement
ifconfigip addr, ip link
routeip route
netstatss
arpip neigh
traceroutetracepath (no root needed)

The ip command from iproute2 replaces ifconfig, route, and arp

πŸ”§ Network Troubleshooting Flow

1. Check interface: ip addr, Is it UP? Has IP?
2. Check gateway: ip route, Default route exists?
3. Ping gateway: ping GATEWAY_IP, Layer 2/3 OK?
4. Ping DNS: ping 8.8.8.8, Internet reachable?
5. DNS test: dig google.com, Name resolution OK?
6. Check firewall: iptables -L / ufw status
16. SSH, Secure Shell

πŸ”‘ SSH Connection Flow

Client runs
ssh user@host
β†’
Connect to
Port 22
β†’
Key Exchange
(Diffie-Hellman)
β†’
Authentication
(key or password)
β†’
Encrypted
Session

⌨️ SSH Commands

CommandDescription
ssh user@hostConnect to remote server
ssh -p 2222 user@hostConnect on custom port
ssh-keygen -t ed25519Generate SSH key pair
ssh-copy-id user@hostCopy public key to server
scp file user@host:/pathSecure copy file to remote
sftp user@hostInteractive secure file transfer
ssh-agent bashStart SSH agent
ssh-add ~/.ssh/id_ed25519Add key to agent
ssh -L 8080:localhost:80 hostLocal port forwarding (tunnel)
ssh -J jump hostSSH via jump host (ProxyJump)
~/.ssh/configClient SSH config (aliases, keys, options) ~/.ssh/authorized_keysAllowed public keys on server ~/.ssh/known_hostsFingerprints of known servers /etc/ssh/sshd_configServer-side SSH configuration

πŸ” SSH Key Authentication Flow

1. Generate key pair: ssh-keygen -t ed25519
2. Copy public key to server: ssh-copy-id user@host
3. Client sends public key fingerprint to server
4. Server checks ~/.ssh/authorized_keys, match found
5. Access granted, no password needed
Ed25519Recommended, fast, secure, short keys RSA (4096-bit)Widely compatible, good fallback ECDSAElliptic curve, faster than RSA

πŸ›‘οΈ SSH Hardening

PermitRootLogin noDisable root SSH login PasswordAuthentication noKey-only authentication Port 2222Change default port (avoid scanners) AllowUsers alice bobWhitelist specific users MaxAuthTries 3Limit login attempts ClientAliveInterval 300Timeout idle sessions (5 min) fail2banBan IPs after failed attempts Key permissions~/.ssh = 700, private key = 600, authorized_keys = 644

After editing /etc/ssh/sshd_config, run: systemctl restart sshd

17. Firewall

🧱 iptables Chain Flow

Incoming Packet
β†’
PREROUTING
β†’
Routing Decision
β†’
INPUT (local)
or FORWARD (transit)
β†’
OUTPUT (local out)
β†’
POSTROUTING
TablePurposeChains
filterAllow/deny packets (default)INPUT, FORWARD, OUTPUT
natNetwork address translationPREROUTING, OUTPUT, POSTROUTING
manglePacket header modificationAll chains
rawSkip connection trackingPREROUTING, OUTPUT

πŸ”΅ UFW (Ubuntu Firewall)

CommandDescription
ufw enableActivate firewall
ufw disableDeactivate firewall
ufw status verboseShow rules and status
ufw allow 22Allow SSH
ufw allow 80/tcpAllow HTTP (TCP only)
ufw deny 3306Block MySQL port
ufw allow from 10.0.0.0/8Allow from subnet
ufw delete allow 80Remove a rule
ufw resetReset to defaults

UFW is a user-friendly frontend for iptables, ideal for Ubuntu servers

πŸ”΄ firewalld (RHEL/CentOS)

CommandDescription
firewall-cmd --stateCheck if running
firewall-cmd --list-allShow all rules
firewall-cmd --add-service=httpAllow HTTP
firewall-cmd --add-port=8080/tcpAllow port 8080
firewall-cmd --remove-port=8080/tcpRemove port rule
firewall-cmd --reloadApply pending changes
firewall-cmd --zone=public --list-allShow zone rules
--permanentPersist across reboots (add to any cmd)

βš–οΈ Firewall Comparison

FeatureiptablesUFWfirewalld
ComplexityHighLowMedium
DistroAnyDebian/UbuntuRHEL/CentOS/Fedora
ZonesNoNoYes
Live reloadImmediateImmediate--reload needed
BackendKernel netfilteriptablesnftables / iptables
nftablesModern replacement for iptables, unified syntax, better performance
18. Linux Security

πŸ›‘οΈ Security Checklist

Update regularlyapt upgrade / dnf upgrade, patch vulnerabilities Use sudo, not rootNever login as root, use sudo for privilege escalation Strong passwordsUse password policies, length, complexity, expiry SSH keys onlyDisable password auth, PasswordAuthentication no Firewall enabledUFW or firewalld, deny all, allow specific Disable unused servicessystemctl disable service, reduce attack surface Monitor logsCheck /var/log/auth.log and journalctl regularly File permissionsPrinciple of least privilege, 600 for secrets, 755 for scripts SELinux / AppArmorMandatory access control, enforcing mode in production Automatic updatesunattended-upgrades (Debian) or dnf-automatic (RHEL)

πŸ”’ SELinux vs AppArmor

SELinux (RHEL)

  • Label-based MAC
  • Very granular control
  • Complex to configure
  • Default on RHEL/CentOS
vs

AppArmor (Ubuntu)

  • Path-based MAC
  • Easier to learn
  • Profile per application
  • Default on Ubuntu/SUSE
getenforceCheck SELinux mode setenforce 1Set SELinux to enforcing sestatusDetailed SELinux status aa-statusAppArmor status

πŸ”§ Security Tools

fail2banAuto-ban IPs after failed logins (SSH brute-force protection) auditdSystem audit daemon, track file access, syscalls rkhunterRootkit detection scanner ClamAVOpen-source antivirus (mail servers, file scanning) lynisSecurity audit tool, scans and scores your system nmapNetwork scanner, find open ports and services OpenSCAPCompliance scanning (CIS benchmarks)

🏰 Hardening Best Practices

Disable root SSHPermitRootLogin no in sshd_config Remove unused packagesapt autoremove / dnf autoremove Password policies/etc/login.defs, PASS_MAX_DAYS, PASS_MIN_LEN Auto updatesunattended-upgrades or dnf-automatic Audit loggingEnable auditd, log file access and privilege use Disk encryptionLUKS for full disk encryption at rest Limit cron/etc/cron.allow, only listed users can use cron Banner warning/etc/issue.net, legal warning before login
19. Text Processing

πŸ”€ Core Text Processing Tools

ToolPurposeExample
grepSearch text by patterngrep "error" /var/log/syslog
sedStream editor (find/replace)sed 's/old/new/g' file
awkColumn processing & reportingawk '(print $1, $3)' file
cutExtract fields / columnscut -d: -f1 /etc/passwd
sortSort linessort -t: -k3 -n /etc/passwd
uniqRemove duplicate linessort file | uniq -c
trTranslate or delete charsecho HELLO | tr A-Z a-z
xargsBuild commands from stdinfind . -name "*.log" | xargs rm
teeWrite to file and stdoutecho hi | tee log.txt

πŸ” grep, Pattern Search

FlagDescription
-iCase insensitive search
-rRecursive (search all files in dir)
-nShow line numbers
-vInvert match (lines NOT matching)
-cCount matching lines
-lShow only filenames with matches
-EExtended regex (egrep)
-wMatch whole words only
-A 3Show 3 lines after match
-B 3Show 3 lines before match

grep -rn "TODO" ., recursively find all TODOs with line numbers

βœ‚οΈ sed, Stream Editor

CommandDescription
sed 's/old/new/'Replace first occurrence per line
sed 's/old/new/g'Replace all occurrences
sed -i 's/old/new/g' fileIn-place edit (modify file)
sed '/pattern/d'Delete lines matching pattern
sed -n '5,10p'Print only lines 5–10
sed '3i\new text'Insert text before line 3
sed '3a\new text'Append text after line 3

Always test without -i first, then add -i to modify in place

πŸ“Š awk, Column Processing

awk '(print $1)'Print first column (space-delimited) awk -F: '(print $1)'Use : as field separator awk '$3 > 1000'Filter rows where column 3 > 1000 awk 'NR==5'Print only line 5 (NR = line number) awk 'END (print NR)'Print total number of lines NFNumber of fields in current line

Pipe chain example:

cat access.log | awk '(print $1)' | sort | uniq -c | sort -rn | head -10

This gets the top 10 IP addresses from an access log

20. Shell Scripting

πŸ“œ Script Basics

Shebang#!/bin/bash, first line tells which interpreter to use VariablesVAR=value (no spaces around =), use with $VAR $1, $2, $3Positional arguments passed to script $@All arguments as separate strings $#Number of arguments $?Exit code of last command (0 = success) $$PID of current script Single quotes'literal', no variable expansion Double quotes"expand $VAR", variables are expanded $(command)Command substitution, capture output Exit codes0 = success, 1-255 = error. Use: exit 0

πŸ”€ Control Structures

StructureSyntax
ifif [ condition ]; then ... elif ...; then ... else ... fi
forfor i in 1 2 3; do echo $i; done
for (C-style)for ((i=0; i<10; i++)); do echo $i; done
whilewhile [ condition ]; do ... done
untiluntil [ condition ]; do ... done
casecase $VAR in pattern1) cmd;; pattern2) cmd;; esac
functionmy_func() ( echo "hello"; ), define reusable block

Test conditions: [ -f file ] (file exists), [ -d dir ] (dir exists), [ -z "$str" ] (empty string)

🧩 Useful Patterns

Read inputread -p "Enter name: " name File exists?if [ -f /path/file ]; then ... fi Dir exists?if [ -d /path/dir ]; then ... fi String compareif [ "$a" = "$b" ]; then ... fi Numeric compare-eq, -ne, -lt, -gt, -le, -ge Arithmeticresult=$((5 + 3)) or let "result = 5 + 3" Arraysarr=(one two three); echo $arr[0] β†’ but use arr notation Cmd substitutiontoday=$(date +%Y-%m-%d) Default valuename=$( 1:-"default" ), if $1 empty, use "default"

βœ… Best Practices

set -euo pipefailExit on error, undefined var, pipe failure Always quote "$VAR"Prevent word splitting and globbing bugs Check return codesif ! command; then echo "failed"; exit 1; fi Use functionsBreak scripts into reusable, testable functions Add loggingecho "[INFO] message" or use logger command Use shellcheckStatic analysis, catches common bugs. Run: shellcheck script.sh Trap signalstrap cleanup EXIT, clean up on script exit Use /bin/bashAvoid /bin/sh if using bash features (arrays, etc.)
21. Linux Quick Reference

πŸ“‹ Master Command Cheat Sheet

CategoryCommandDescription
NavigationpwdPrint working directory
ls -laList all files with details
cd /pathChange directory
find / -name "file"Find files by name
tree -L 2Show directory tree
Filescp -r src destCopy files/directories
mv old newMove or rename
rm -rf dirRemove directory (caution!)
cat / less / head / tailView file contents
tar -czf archive.tar.gz dir/Create compressed archive
Permissionschmod 755 fileChange file mode
chown user:group fileChange owner and group
umask 022Set default permissions
ls -laView permissions
Usersuseradd -m userCreate user with home dir
passwd userSet user password
usermod -aG group userAdd user to group
sudo commandRun as superuser
Packagesapt update && apt upgradeUpdate packages (Debian)
apt install pkgInstall package (Debian)
dnf install pkgInstall package (RHEL)
apt search pkgSearch packages
Processesps auxList all processes
top / htopLive process monitor
kill -15 PIDGracefully stop process
kill -9 PIDForce kill process
systemctl status serviceCheck service status
Networkip addrShow IP addresses
ss -tlnpShow listening ports
ping hostTest connectivity
curl -I urlHTTP headers check
dig domainDNS lookup
Diskdf -hDisk space usage
du -sh dir/Directory size
lsblkList block devices
free -hMemory usage
Logsjournalctl -u serviceView service logs
tail -f /var/log/syslogFollow live logs
dmesg | tailRecent kernel messages
Servicessystemctl start serviceStart a service
systemctl enable serviceEnable at boot
systemctl restart serviceRestart a service
systemctl daemon-reloadReload unit files
SSHssh user@hostConnect to remote server
ssh-keygen -t ed25519Generate SSH key pair
scp file user@host:/pathSecure copy to remote