Learning state
Track this guide
Saved in this browser only. No account required.
Linux System Administration Master Class
Engineering-Grade Reference Manual for Linux System Administration
A comprehensive guide to essential Linux commands and system administration with real-world examples
Table of Contents
- File System Navigation & Management
- File Permissions & Ownership
- Process Management
- System Monitoring & Performance
- Network Administration
- User & Group Management
- Service Management (systemd)
- Log Management
- Package Management
- SSH & Remote Access
- Disk & Storage Management
- Security & Hardening
File System Navigation & Management
🔹 Command: ls
✔️ What It Does
Lists directory contents with various formatting and filtering options.
✔️ Syntax Examples
# Basic: List files in current directory
ls
# Real-world: Detailed list with human-readable sizes
ls -lah
# Production: Sort by modification time, newest first
ls -lt /var/log/
# Show only directories
ls -d */
# Recursive listing with full paths
ls -R /etc/nginx/
✔️ Notes, Tips & Common Mistakes
-l= long format,-a= show hidden files,-h= human-readable sizes-tsorts by time,-Ssorts by size- Hidden files start with
.(use-ato see them) - Use
ls -ito see inode numbers (useful for finding hard links)
🔹 Command: cd
✔️ What It Does
Changes the current working directory.
✔️ Syntax Examples
# Basic: Change to specific directory
cd /var/log
# Go to home directory
cd ~
# or just
cd
# Go to previous directory
cd -
# Go up one level
cd ..
# Go up two levels
cd ../..
✔️ Notes, Tips & Common Mistakes
cd -toggles between current and previous directory~represents home directory (/home/username)- Use tab completion to avoid typos
cdwithout arguments goes to home directory
🔹 Command: pwd
✔️ What It Does
Prints the current working directory (full absolute path).
✔️ Syntax Examples
# Show current directory
pwd
# Use in scripts to get current location
CURRENT_DIR=$(pwd)
echo "Working in: $CURRENT_DIR"
✔️ Notes, Tips & Common Mistakes
- Essential for scripts to determine execution context
- Use
-Pto show physical path (resolves symlinks)
🔹 Command: mkdir
✔️ What It Does
Creates new directories.
✔️ Syntax Examples
# Basic: Create single directory
mkdir mydir
# Real-world: Create nested directories
mkdir -p /app/data/logs/archive
# Production: Create with specific permissions
mkdir -m 755 /var/www/html/uploads
# Create multiple directories
mkdir dir1 dir2 dir3
✔️ Notes, Tips & Common Mistakes
-pcreates parent directories as needed (no error if exists)-msets permissions during creation- Always use
-pin scripts for idempotency
🔹 Command: rm
✔️ What It Does
Removes files and directories. USE WITH EXTREME CAUTION.
✔️ Syntax Examples
# Basic: Remove a file
rm file.txt
# Real-world: Remove directory and contents
rm -rf /tmp/old-data
# Production: Interactive removal (asks confirmation)
rm -i important-file.txt
# Remove files older than 7 days
find /tmp -type f -mtime +7 -delete
✔️ Notes, Tips & Common Mistakes
- NEVER run
rm -rf /orrm -rf /*(destroys system) -r= recursive (for directories),-f= force (no prompts)- Use
-ifor interactive mode when unsure - No trash/recycle bin - deletion is permanent
- Always double-check paths before running with
-rf
🔹 Command: cp
✔️ What It Does
Copies files and directories.
✔️ Syntax Examples
# Basic: Copy file
cp source.txt destination.txt
# Real-world: Copy directory recursively
cp -r /app/config /backup/config-$(date +%Y%m%d)
# Production: Copy preserving attributes and show progress
cp -av /data/important /backup/
# Copy only if source is newer
cp -u source.txt dest.txt
✔️ Notes, Tips & Common Mistakes
-rfor directories,-apreserves all attributes (archive mode)-vshows verbose output,-iprompts before overwrite- Use
-pto preserve timestamps and permissions -uonly copies if source is newer (useful for backups)
🔹 Command: mv
✔️ What It Does
Moves or renames files and directories.
✔️ Syntax Examples
# Basic: Rename file
mv oldname.txt newname.txt
# Real-world: Move file to different directory
mv /tmp/upload.csv /data/processed/
# Production: Move with backup of existing file
mv -b config.yml config.yml.bak
# Move multiple files
mv *.log /var/log/archive/
✔️ Notes, Tips & Common Mistakes
- Moving within same filesystem is instant (just updates metadata)
- Moving across filesystems copies then deletes (slower)
-iprompts before overwriting,-nnever overwrites- No
-rneeded for directories
🔹 Command: find
✔️ What It Does
Searches for files and directories based on various criteria. Extremely powerful for system administration.
✔️ Syntax Examples
# Basic: Find files by name
find /var/log -name "*.log"
# Real-world: Find files modified in last 24 hours
find /app/data -type f -mtime -1
# Production: Find and delete old log files
find /var/log -name "*.log" -mtime +30 -delete
# Find large files (>100MB)
find / -type f -size +100M
# Find files and execute command
find /tmp -name "*.tmp" -exec rm {} \;
# Find with multiple conditions
find /var/www -type f -name "*.php" -mtime -7 -user www-data
✔️ Notes, Tips & Common Mistakes
-type f= files,-type d= directories-mtime +7= modified more than 7 days ago,-mtime -7= within 7 days-execruns command on each result ({}is placeholder,\;ends command)- Use
-deletecarefully - test with-printfirst -nameis case-sensitive, use-inamefor case-insensitive
🔹 Command: grep
✔️ What It Does
Searches for patterns in files or input streams. Essential for log analysis and troubleshooting.
✔️ Syntax Examples
# Basic: Search for text in file
grep "error" /var/log/syslog
# Real-world: Case-insensitive recursive search
grep -ri "database connection" /var/log/
# Production: Show context around matches
grep -C 3 "FATAL" /var/log/app.log
# Count occurrences
grep -c "404" /var/log/nginx/access.log
# Invert match (show lines NOT matching)
grep -v "DEBUG" app.log
# Multiple patterns
grep -E "error|warning|critical" /var/log/syslog
# Show only matching part
grep -o "IP: [0-9.]*" access.log
✔️ Notes, Tips & Common Mistakes
-i= case-insensitive,-r= recursive,-n= show line numbers-vinverts match (shows non-matching lines)-Eenables extended regex,-Penables Perl regex-A 5shows 5 lines after,-B 5shows 5 before,-C 5shows both- Combine with
tail -ffor real-time log monitoring
File Permissions & Ownership
🔹 Command: chmod
✔️ What It Does
Changes file permissions (read, write, execute) for owner, group, and others.
✔️ Syntax Examples
# Basic: Make file executable
chmod +x script.sh
# Real-world: Set specific permissions (rwxr-xr-x)
chmod 755 /usr/local/bin/myapp
# Production: Recursive permission change
chmod -R 644 /var/www/html/*.html
# Remove write permission for group and others
chmod go-w sensitive-file.txt
# Set directory permissions for web server
chmod 755 /var/www/html
chmod 644 /var/www/html/*.html
✔️ Permission Numbers
7= rwx (read, write, execute)6= rw- (read, write)5= r-x (read, execute)4= r-- (read only)0= --- (no permissions)
Format: [owner][group][others]
755= rwxr-xr-x (owner full, others read+execute)644= rw-r--r-- (owner read+write, others read only)600= rw------- (owner only)
✔️ Notes, Tips & Common Mistakes
- Directories need execute permission to be entered
755for directories and executables,644for regular files- Never use
777in production (security risk) - Use
-Rcarefully - can break system if misused
🔹 Command: chown
✔️ What It Does
Changes file owner and group ownership.
✔️ Syntax Examples
# Basic: Change owner
chown john file.txt
# Real-world: Change owner and group
chown john:developers project/
# Production: Recursive ownership change
chown -R www-data:www-data /var/www/html
# Change only group
chown :nginx /var/log/nginx/access.log
✔️ Notes, Tips & Common Mistakes
- Format:
chown user:group file - Requires root/sudo privileges
- Use
-Rfor recursive changes - Common web server:
www-data:www-dataornginx:nginx
🔹 Command: umask
✔️ What It Does
Sets default permissions for newly created files and directories.
✔️ Syntax Examples
# Show current umask
umask
# Set umask (files: 644, dirs: 755)
umask 022
# Restrictive umask (files: 600, dirs: 700)
umask 077
# Add to .bashrc for persistence
echo "umask 022" >> ~/.bashrc
✔️ Notes, Tips & Common Mistakes
- Default umask is usually
022 - Umask
022creates files as644and directories as755 - Umask
077creates files as600and directories as700 - Set in shell config files for persistence
Process Management
🔹 Command: ps
✔️ What It Does
Displays information about running processes.
✔️ Syntax Examples
# Basic: Show processes for current user
ps
# Real-world: Show all processes with details
ps aux
# Production: Show process tree
ps auxf
# Find specific process
ps aux | grep nginx
# Show processes for specific user
ps -u www-data
# Custom format output
ps -eo pid,ppid,cmd,%mem,%cpu --sort=-%mem | head
✔️ Notes, Tips & Common Mistakes
ps auxis most common (all users, detailed info)a= all users,u= user-oriented format,x= include processes without TTY- Combine with
grepto find specific processes - Use
pgrepfor simpler process searching
🔹 Command: top / htop
✔️ What It Does
Real-time view of system processes, CPU, and memory usage.
✔️ Syntax Examples
# Basic: Launch top
top
# Real-world: Show specific user's processes
top -u www-data
# Production: Batch mode for logging
top -b -n 1 > system-snapshot.txt
# htop (better interface, if installed)
htop
✔️ Interactive Commands in top
M= sort by memoryP= sort by CPUk= kill processq= quit1= show individual CPU cores
✔️ Notes, Tips & Common Mistakes
htopis more user-friendly but may need installation- Press
hfor help inside top - Load average shows 1, 5, and 15-minute averages
- Load > number of CPU cores indicates system strain
🔹 Command: kill
✔️ What It Does
Sends signals to processes, typically to terminate them.
✔️ Syntax Examples
# Basic: Gracefully terminate process
kill 1234
# Real-world: Force kill unresponsive process
kill -9 1234
# Production: Graceful shutdown (SIGTERM)
kill -15 $(pgrep nginx)
# Reload configuration (SIGHUP)
kill -HUP $(pgrep nginx)
# Kill all processes by name
pkill nginx
# Kill all user processes
pkill -u username
✔️ Common Signals
SIGTERM (15)= graceful shutdown (default)SIGKILL (9)= force kill (cannot be caught)SIGHUP (1)= reload configurationSIGINT (2)= interrupt (Ctrl+C)
✔️ Notes, Tips & Common Mistakes
- Always try
kill(SIGTERM) beforekill -9 kill -9doesn't allow cleanup (use as last resort)- Use
pgrepto find PID by name killallkills all processes with given name
🔹 Command: systemctl
✔️ What It Does
Controls systemd services (modern Linux service manager).
✔️ Syntax Examples
# Basic: Start a service
systemctl start nginx
# Real-world: Enable service to start on boot
systemctl enable nginx
systemctl start nginx
# Production: Check service status
systemctl status nginx
# Restart service
systemctl restart nginx
# Reload configuration without restart
systemctl reload nginx
# Stop and disable service
systemctl stop nginx
systemctl disable nginx
# List all running services
systemctl list-units --type=service --state=running
# View service logs
journalctl -u nginx -f
✔️ Notes, Tips & Common Mistakes
enable= start on boot,start= start now (do both)reloadis gentler thanrestart(no downtime)- Use
systemctl daemon-reloadafter editing service files - Check status before and after changes
System Monitoring & Performance
🔹 Command: df
✔️ What It Does
Shows disk space usage for mounted filesystems.
✔️ Syntax Examples
# Basic: Show disk usage
df
# Real-world: Human-readable format
df -h
# Production: Show specific filesystem type
df -h -t ext4
# Show inodes usage
df -i
# Exclude certain filesystem types
df -h -x tmpfs -x devtmpfs
✔️ Notes, Tips & Common Mistakes
-hmakes output human-readable (GB, MB)- Watch for filesystems at >90% capacity
- Inode exhaustion can occur even with free space
- Use with
duto find what's using space
🔹 Command: du
✔️ What It Does
Shows disk usage of files and directories.
✔️ Syntax Examples
# Basic: Show size of directory
du /var/log
# Real-world: Human-readable summary
du -sh /var/log/*
# Production: Find largest directories
du -h /var | sort -rh | head -20
# Show only total for directory
du -sh /home/user
# Exclude certain patterns
du -h --exclude="*.log" /app
✔️ Notes, Tips & Common Mistakes
-s= summary only,-h= human-readable- Combine with
sort -rhto find largest items - Use
--max-depth=1to limit recursion - Can be slow on large filesystems
🔹 Command: free
✔️ What It Does
Displays memory (RAM) usage statistics.
✔️ Syntax Examples
# Basic: Show memory usage
free
# Real-world: Human-readable format
free -h
# Production: Show in MB and update every 2 seconds
free -m -s 2
# Show total line
free -h -t
✔️ Notes, Tips & Common Mistakes
- "Available" is more important than "free" (includes cache)
- Linux uses free RAM for cache (this is good)
- Swap usage indicates memory pressure
- High swap usage = need more RAM
🔹 Command: vmstat
✔️ What It Does
Reports virtual memory statistics, processes, CPU activity.
✔️ Syntax Examples
# Basic: Show current stats
vmstat
# Real-world: Update every 2 seconds
vmstat 2
# Production: 10 samples, 5 seconds apart
vmstat 5 10
# Show in MB
vmstat -S M
✔️ Notes, Tips & Common Mistakes
- First line shows averages since boot (ignore it)
- Watch
siandso(swap in/out) - should be near zero - High
wa(wait time) indicates I/O bottleneck rcolumn shows processes waiting for CPU
🔹 Command: iostat
✔️ What It Does
Reports CPU and I/O statistics for devices and partitions.
✔️ Syntax Examples
# Basic: Show CPU and I/O stats
iostat
# Real-world: Extended stats every 2 seconds
iostat -x 2
# Production: Show specific device
iostat -x sda 5
# Human-readable with MB/s
iostat -xm 2
✔️ Notes, Tips & Common Mistakes
- High
%iowaitindicates disk bottleneck awaitshows average wait time for I/O%utilnear 100% means disk is saturated- May need
sysstatpackage installed
Network Administration
🔹 Command: ip
✔️ What It Does
Modern network configuration tool (replaces older ifconfig).
✔️ Syntax Examples
# Basic: Show all network interfaces
ip addr show
# Real-world: Show specific interface
ip addr show eth0
# Production: Add IP address
ip addr add 192.168.1.100/24 dev eth0
# Show routing table
ip route show
# Add static route
ip route add 10.0.0.0/24 via 192.168.1.1
# Show ARP table
ip neigh show
✔️ Notes, Tips & Common Mistakes
- Replaces deprecated
ifconfig,route,arp - Changes are not persistent (use network config files)
ip ais shorthand forip addr show- Use
ip -s linkfor interface statistics
🔹 Command: netstat / ss
✔️ What It Does
Shows network connections, routing tables, interface statistics. ss is the modern replacement.
✔️ Syntax Examples
# Basic: Show all connections
ss -tuln
# Real-world: Show listening ports
ss -tlnp
# Production: Find what's using port 80
ss -tlnp | grep :80
# Show established connections
ss -tn state established
# netstat equivalent (older)
netstat -tuln
✔️ Flags Explained
-t= TCP,-u= UDP-l= listening,-n= numeric (no DNS lookup)-p= show process (requires root)
✔️ Notes, Tips & Common Mistakes
ssis faster thannetstaton busy systems- Use
-nto avoid slow DNS lookups -prequires root to show process names- Check for unexpected listening ports (security)
🔹 Command: ping
✔️ What It Does
Tests network connectivity to a host.
✔️ Syntax Examples
# Basic: Ping host
ping google.com
# Real-world: Send only 4 packets
ping -c 4 192.168.1.1
# Production: Set interval and timeout
ping -c 10 -i 0.5 -W 2 server.example.com
# Flood ping (testing, requires root)
ping -f localhost
✔️ Notes, Tips & Common Mistakes
-climits packet count (otherwise runs forever)-isets interval between packets-Wsets timeout for response- Some servers block ICMP (ping may fail even if host is up)
🔹 Command: curl / wget
✔️ What It Does
Downloads files and tests HTTP endpoints. curl is more versatile, wget better for recursive downloads.
✔️ Syntax Examples
# Basic: Download file
curl -O https://example.com/file.zip
wget https://example.com/file.zip
# Real-world: Test API endpoint
curl -X POST -H "Content-Type: application/json" \
-d '{"key":"value"}' https://api.example.com/endpoint
# Production: Download with retry and timeout
curl --retry 3 --max-time 30 -o output.tar.gz https://example.com/file.tar.gz
# Follow redirects
curl -L https://example.com
# Show only headers
curl -I https://example.com
# Test with authentication
curl -u username:password https://api.example.com
✔️ Notes, Tips & Common Mistakes
curl -Opreserves filename,-ospecifies output name-Lfollows redirects (important for many URLs)-Ior--headfor headers only (useful for testing)wget -rfor recursive downloads
🔹 Command: ufw / iptables
✔️ What It Does
Manages firewall rules. ufw is user-friendly frontend for iptables.
✔️ Syntax Examples
# Basic: Enable firewall
ufw enable
# Real-world: Allow specific port
ufw allow 22/tcp
ufw allow 80/tcp
ufw allow 443/tcp
# Production: Allow from specific IP
ufw allow from 192.168.1.100 to any port 22
# Deny specific port
ufw deny 3306/tcp
# Show status and rules
ufw status verbose
# Delete rule
ufw delete allow 80/tcp
✔️ Notes, Tips & Common Mistakes
- Always allow SSH (port 22) before enabling firewall
- Rules are processed in order
ufwis simpler thaniptablesfor basic needs- Test rules before applying in production
User & Group Management
🔹 Command: useradd / adduser
✔️ What It Does
Creates new user accounts. adduser is more interactive and user-friendly.
✔️ Syntax Examples
# Basic: Create user (Debian/Ubuntu)
adduser john
# Real-world: Create system user for service
useradd -r -s /bin/false -d /var/lib/myapp myapp
# Production: Create user with specific UID and groups
useradd -u 1500 -g developers -G docker,sudo -m -s /bin/bash john
# Create user without home directory
useradd -M serviceuser
✔️ Notes, Tips & Common Mistakes
adduseris interactive (Debian/Ubuntu),useraddis low-level-mcreates home directory,-ssets shell-rcreates system user (UID < 1000)- Always set password after:
passwd username
🔹 Command: usermod
✔️ What It Does
Modifies existing user accounts.
✔️ Syntax Examples
# Basic: Add user to group
usermod -aG docker john
# Real-world: Change user's shell
usermod -s /bin/zsh john
# Production: Lock user account
usermod -L john
# Unlock account
usermod -U john
# Change home directory
usermod -d /new/home -m john
✔️ Notes, Tips & Common Mistakes
-aGappends to groups (without-a, replaces all groups)- User must log out and back in for group changes to take effect
-Llocks account (disables password),-Uunlocks
🔹 Command: passwd
✔️ What It Does
Changes user passwords.
✔️ Syntax Examples
# Basic: Change your own password
passwd
# Real-world: Change another user's password (requires root)
passwd john
# Production: Force password change on next login
passwd -e john
# Lock/unlock account
passwd -l john # lock
passwd -u john # unlock
# Set password expiry
passwd -x 90 john # expire after 90 days
✔️ Notes, Tips & Common Mistakes
- Enforce strong password policies
- Use
-eto force password change on first login - Consider using SSH keys instead of passwords
Service Management (systemd)
🔹 Creating Custom Services
✔️ What It Does
Defines how systemd should manage your application as a service.
✔️ Example Service File
Create /etc/systemd/system/myapp.service:
[Unit]
Description=My Application
After=network.target
[Service]
Type=simple
User=myapp
WorkingDirectory=/opt/myapp
ExecStart=/opt/myapp/bin/start.sh
Restart=always
RestartSec=10
[Install]
WantedBy=multi-user.target
✔️ Enable and Start
# Reload systemd to recognize new service
systemctl daemon-reload
# Enable and start service
systemctl enable myapp
systemctl start myapp
# Check status
systemctl status myapp
✔️ Notes, Tips & Common Mistakes
- Place service files in
/etc/systemd/system/ - Run
daemon-reloadafter editing service files - Use
Type=simplefor foreground processes Restart=alwaysensures service restarts on failure
Log Management
🔹 Command: journalctl
✔️ What It Does
Queries and displays logs from systemd journal.
✔️ Syntax Examples
# Basic: Show all logs
journalctl
# Real-world: Follow logs in real-time
journalctl -f
# Production: Show logs for specific service
journalctl -u nginx -f
# Show logs since boot
journalctl -b
# Show logs from last hour
journalctl --since "1 hour ago"
# Show logs between dates
journalctl --since "2024-01-01" --until "2024-01-31"
# Show only errors
journalctl -p err
# Show kernel messages
journalctl -k
✔️ Notes, Tips & Common Mistakes
-ufilters by service unit-ffollows logs (liketail -f)-pfilters by priority (emerg, alert, crit, err, warning, notice, info, debug)- Logs can grow large; configure rotation
🔹 Command: tail
✔️ What It Does
Displays the last part of files, commonly used for log monitoring.
✔️ Syntax Examples
# Basic: Show last 10 lines
tail /var/log/syslog
# Real-world: Follow log file in real-time
tail -f /var/log/nginx/access.log
# Production: Show last 100 lines and follow
tail -n 100 -f /var/log/app.log
# Follow multiple files
tail -f /var/log/nginx/*.log
# Show last 50 lines
tail -n 50 /var/log/syslog
✔️ Notes, Tips & Common Mistakes
-ffollows file (shows new lines as they're added)-nspecifies number of lines- Combine with
grepfor filtering:tail -f app.log | grep ERROR - Use
Ctrl+Cto stop following
Package Management
🔹 Command: apt (Debian/Ubuntu)
✔️ What It Does
Manages software packages on Debian-based systems.
✔️ Syntax Examples
# Basic: Update package list
apt update
# Real-world: Upgrade all packages
apt update && apt upgrade -y
# Production: Install specific package
apt install nginx -y
# Remove package
apt remove nginx
# Remove package and config files
apt purge nginx
# Search for package
apt search docker
# Show package information
apt show nginx
# Clean up unused packages
apt autoremove
✔️ Notes, Tips & Common Mistakes
- Always run
apt updatebeforeapt install -yauto-confirms (useful for scripts)upgradeupdates packages,dist-upgradehandles dependencies betterautoremovecleans up orphaned dependencies
🔹 Command: yum / dnf (RHEL/CentOS/Fedora)
✔️ What It Does
Manages packages on Red Hat-based systems. dnf is the modern replacement for yum.
✔️ Syntax Examples
# Basic: Install package
dnf install nginx
# Real-world: Update all packages
dnf update -y
# Production: Search for package
dnf search docker
# List installed packages
dnf list installed
# Remove package
dnf remove nginx
# Clean cache
dnf clean all
✔️ Notes, Tips & Common Mistakes
dnfis faster and more modern thanyum- Use
dnf historyto see package changes dnf provides */filenamefinds which package provides a file
SSH & Remote Access
🔹 Command: ssh
✔️ What It Does
Securely connects to remote systems.
✔️ Syntax Examples
# Basic: Connect to server
ssh user@server.com
# Real-world: Connect with specific key
ssh -i ~/.ssh/id_rsa_prod user@server.com
# Production: Execute command remotely
ssh user@server.com "systemctl status nginx"
# Port forwarding (tunnel)
ssh -L 8080:localhost:80 user@server.com
# Copy SSH key to server
ssh-copy-id user@server.com
✔️ Notes, Tips & Common Mistakes
- Use SSH keys instead of passwords (more secure)
- Configure
~/.ssh/configfor frequently accessed servers -pspecifies custom port:ssh -p 2222 user@server.com- Use
-vfor verbose debugging
🔹 Command: scp
✔️ What It Does
Securely copies files between systems over SSH.
✔️ Syntax Examples
# Basic: Copy file to remote server
scp file.txt user@server.com:/path/to/destination/
# Real-world: Copy directory recursively
scp -r /local/dir user@server.com:/remote/dir
# Production: Copy from remote to local
scp user@server.com:/remote/file.txt /local/path/
# Use specific SSH key
scp -i ~/.ssh/id_rsa file.txt user@server.com:/path/
✔️ Notes, Tips & Common Mistakes
-rfor directories (recursive)-Pspecifies port (capital P, unlike ssh's lowercase -p)- Consider
rsyncfor large transfers (supports resume)
🔹 Command: rsync
✔️ What It Does
Efficiently synchronizes files and directories between locations.
✔️ Syntax Examples
# Basic: Sync directory to remote
rsync -av /local/dir/ user@server.com:/remote/dir/
# Real-world: Sync with progress and compression
rsync -avz --progress /local/ user@server.com:/remote/
# Production: Sync with delete (mirror)
rsync -av --delete /source/ /destination/
# Exclude patterns
rsync -av --exclude='*.log' --exclude='node_modules' /app/ backup/
# Dry run (test without changes)
rsync -avn /source/ /dest/
✔️ Notes, Tips & Common Mistakes
- Trailing slash matters:
/dir/syncs contents,/dirsyncs directory itself -a= archive mode (preserves permissions, timestamps, etc.)-v= verbose,-z= compress during transfer--deleteremoves files in destination not in source (use carefully)-n= dry run (preview changes)
Disk & Storage Management
🔹 Command: mount / umount
✔️ What It Does
Mounts and unmounts filesystems.
✔️ Syntax Examples
# Basic: Show mounted filesystems
mount
# Real-world: Mount USB drive
mount /dev/sdb1 /mnt/usb
# Production: Mount with specific options
mount -o ro,noexec /dev/sdb1 /mnt/data
# Unmount filesystem
umount /mnt/usb
# Force unmount (if busy)
umount -f /mnt/usb
✔️ Notes, Tips & Common Mistakes
- Edit
/etc/fstabfor persistent mounts ro= read-only,rw= read-writenoexecprevents execution of binaries (security)- Use
lsblkto see available block devices
🔹 Command: lsblk
✔️ What It Does
Lists information about block devices (disks, partitions).
✔️ Syntax Examples
# Basic: List all block devices
lsblk
# Real-world: Show filesystem types
lsblk -f
# Production: Show size in bytes
lsblk -b
✔️ Notes, Tips & Common Mistakes
- Shows device tree structure
- Useful before mounting/partitioning
-fshows filesystem type and UUID
Security & Hardening
🔹 Security Best Practices
✔️ Essential Security Commands
# Check for failed login attempts
grep "Failed password" /var/log/auth.log
# List users with sudo access
grep -Po '^sudo.+:\K.*$' /etc/group
# Find files with SUID bit (potential security risk)
find / -perm -4000 -type f 2>/dev/null
# Check listening ports
ss -tlnp
# Review cron jobs
crontab -l
ls -la /etc/cron.*
# Check last logins
last
lastlog
# Monitor file changes
find /etc -type f -mtime -1
✔️ Hardening Checklist
- Keep system updated:
apt update && apt upgrade - Configure firewall:
ufw enable - Disable root SSH login: Edit
/etc/ssh/sshd_config - Use SSH keys, disable password auth
- Install fail2ban for brute-force protection
- Regular security audits with
lynis - Monitor logs regularly
- Principle of least privilege for users
- Remove unnecessary services
- Enable automatic security updates
Quick Reference: Common Tasks
System Information
# OS version
cat /etc/os-release
# Kernel version
uname -r
# System uptime
uptime
# Hardware info
lscpu
lshw
Performance Troubleshooting
# High CPU usage
top -o %CPU
ps aux --sort=-%cpu | head
# High memory usage
ps aux --sort=-%mem | head
free -h
# Disk I/O issues
iostat -x 2
iotop
# Network issues
ss -s
netstat -i
Emergency Recovery
# Kill all user processes
pkill -u username
# Force sync and reboot
sync && reboot -f
# Check filesystem
fsck /dev/sda1
# Boot into single-user mode
# Add 'single' to kernel parameters in GRUB
🎓 Linux System Administration Master Class Complete
This comprehensive guide covers essential commands for managing Linux systems in production environments. Practice these commands regularly to build muscle memory and confidence.