Command Line Mastery
Duration: 1.5 hours | Foundation Track
Learning Objectives
- Understand why command line skills are essential for IT professionals
- Master advanced Windows and Linux command line techniques
- Create automation scripts for repetitive tasks
- Implement system monitoring and maintenance scripts
- Develop troubleshooting methodologies using command line tools
Why Learn Command Line?
Command Line vs Graphical Interface
Graphical Interface (GUI):
- Point and click with mouse
- Visual menus and icons
- Good for simple, one-time tasks
- Slower for repetitive actions
Command Line Interface (CLI):
- Type commands directly
- No graphics, just text
- Excellent for automation and scripting
- Much faster for experienced users
Real-World Example
Task: Create 50 user accounts
GUI Method:
- Open User Management
- Click "New User"
- Fill out form
- Click "Create"
- Repeat 49 more times
Time: ~2 hours
Command Line Method:
- Write a script with one command per user
- Run the script
- All 50 users created automatically
Time: ~10 minutes
Windows Command Line Essentials
Command Prompt vs PowerShell
Command Prompt (cmd):
- Traditional Windows command line
- Basic file operations
- Legacy system, but still useful
PowerShell:
- Modern, powerful command line
- Object-oriented (not just text)
- Excellent for system administration
- Can do everything cmd can do, plus much more
Essential Windows Commands
Navigation and File Operations
# Navigation
dir # List files and directories (like ls in Linux)
cd Documents # Change to Documents directory
cd \ # Go to root of current drive
cd .. # Go up one directory
# File operations
copy file1.txt file2.txt # Copy file
move file1.txt C:\backup\ # Move file
del file.txt # Delete file
mkdir newfolder # Create directory
rmdir emptyfolder # Remove empty directory
# Advanced file operations
xcopy C:\source C:\backup /E /H /Y # Copy directory with subdirectories
robocopy C:\source C:\backup /MIR # Mirror directories (robust copy)
System Information and Management
# System details
systeminfo # Detailed system information
whoami # Current user name
hostname # Computer name
ipconfig # Network configuration
ipconfig /all # Detailed network information
# Process management
tasklist # Show running programs (like Task Manager)
taskkill /im notepad.exe # Kill a program
taskkill /f /im explorer.exe # Force kill a program
# Network diagnostics
ping google.com # Test connectivity
tracert google.com # Trace route to destination
nslookup google.com # DNS lookup
netstat -an # Show network connections
PowerShell Advanced Commands
# Get system information
Get-ComputerInfo # Detailed computer information
Get-Service # List all services
Get-Process # List running processes
Get-EventLog System -Newest 10 # Get recent system events
# User management
Get-LocalUser # List local users
New-LocalUser -Name "john" -Description "Marketing User"
Add-LocalGroupMember -Group "Users" -Member "john"
# File operations with filters
Get-ChildItem -Path C:\ -Recurse -Name "*.log" # Find all .log files
Get-Content logfile.txt | Select-String "ERROR" # Find lines containing "ERROR"
# Remote management
Enter-PSSession -ComputerName Server01 # Connect to remote computer
Invoke-Command -ComputerName Server01 -ScriptBlock { Get-Service }
Linux Command Line Power
Text Processing - Linux Specialty
Linux excels at processing text files, logs, and data.
# Search for specific text
grep "error" /var/log/syslog # Find lines containing "error"
grep -i "failed" /var/log/syslog # Case-insensitive search
grep -r "password" /etc/ # Search recursively in directory
grep -n "error" /var/log/syslog # Show line numbers
# Count and sort data
wc -l file.txt # Count lines in file
sort file.txt # Sort lines alphabetically
uniq file.txt # Remove duplicate lines
cut -d',' -f1 data.csv # Extract first column from CSV
# Combine commands with pipes
cat /var/log/syslog | grep "error" | wc -l # Count error lines
ps aux | grep apache # Find Apache processes
df -h | grep -v tmpfs # Show disk usage, exclude tmpfs
System Monitoring Commands
# Performance monitoring
top # Live view of running processes (like Task Manager)
htop # Enhanced version of top (if installed)
free -h # Memory usage in human-readable format
df -h # Disk space usage
du -sh /home/* # Directory sizes
# Network monitoring
netstat -tuln # Show listening ports
ss -tuln # Modern replacement for netstat
ping google.com # Test network connectivity
curl -I website.com # Test web server response
wget -O - http://site.com | grep "title" # Download and search web page
# Process and service monitoring
ps aux | sort -k 3 -nr | head -10 # Top 10 CPU-using processes
systemctl --failed # Show failed services
journalctl -p err -n 10 # Show last 10 error messages
File and Directory Advanced Operations
# Find and locate
find /home -name "*.txt" -mtime -7 # Find .txt files modified in last 7 days
find /var/log -size +100M # Find files larger than 100MB
locate filename # Quick file location (if updatedb is run)
which command # Show location of command
# Archive and compression
tar -czf backup.tar.gz /home/user/ # Create compressed archive
tar -xzf backup.tar.gz # Extract compressed archive
zip -r archive.zip /home/user/ # Create ZIP archive
unzip archive.zip # Extract ZIP archive
# File comparison and synchronization
diff file1.txt file2.txt # Compare two files
rsync -av /source/ /destination/ # Synchronize directories
rsync -av user@remote:/source/ /local/ # Synchronize from remote server
Automation and Scripting
When to Automate
Good Candidates for Automation:
- Tasks performed daily/weekly/monthly
- Tasks involving multiple steps
- Tasks prone to human error
- Repetitive file operations
- System monitoring and reporting
- Backup operations
Business Automation Examples:
- Daily Reports: Automatically generate and email daily sales reports
- User Management: Bulk create user accounts for new employees
- System Maintenance: Automatic cleanup of old log files
- Backup Verification: Check that all backups completed successfully
- Security Monitoring: Alert when suspicious login attempts occur
Windows Batch Files
Basic Batch File Structure:
@echo off
REM This is a comment
echo Starting daily maintenance...
REM Set variables
set BACKUP_DIR=C:\Backups
set DATE=%date:~-4,4%%date:~-10,2%%date:~-7,2%
REM Create backup folder with today's date
mkdir %BACKUP_DIR%\%DATE%
REM Copy important files
xcopy "C:\Important Files" "%BACKUP_DIR%\%DATE%" /E /H /Y
REM Log the backup
echo Backup completed at %time% >> %BACKUP_DIR%\backup.log
echo Daily backup completed!
pause
Advanced PowerShell Script:
# System health check script
param(
[string]$ComputerName = $env:COMPUTERNAME,
[string]$ReportPath = "C:\Reports\HealthCheck.html"
)
# Get system information
$ComputerInfo = Get-ComputerInfo
$Services = Get-Service | Where-Object {$_.Status -eq 'Stopped' -and $_.StartType -eq 'Automatic'}
$DiskInfo = Get-WmiObject -Class Win32_LogicalDisk | Where-Object {$_.DriveType -eq 3}
# Create HTML report
$HTML = @"
<html>
<head><title>System Health Report - $ComputerName</title></head>
<body>
<h1>System Health Report</h1>
<h2>Computer: $ComputerName</h2>
<h2>Date: $(Get-Date)</h2>
<h3>System Information</h3>
<p>OS: $($ComputerInfo.WindowsProductName)</p>
<p>Total Memory: $([math]::Round($ComputerInfo.TotalPhysicalMemory/1GB,2)) GB</p>
<p>Uptime: $((Get-Date) - $ComputerInfo.LastBootUpTime)</p>
<h3>Disk Space</h3>
<table border="1">
<tr><th>Drive</th><th>Size</th><th>Free Space</th><th>% Free</th></tr>
"@
foreach ($Disk in $DiskInfo) {
$PercentFree = [math]::Round(($Disk.FreeSpace / $Disk.Size) * 100, 2)
$HTML += "<tr><td>$($Disk.DeviceID)</td><td>$([math]::Round($Disk.Size/1GB,2)) GB</td><td>$([math]::Round($Disk.FreeSpace/1GB,2)) GB</td><td>$PercentFree%</td></tr>"
}
$HTML += "</table></body></html>"
# Save report
$HTML | Out-File -FilePath $ReportPath
Write-Host "Health check report saved to $ReportPath"
Linux Shell Scripts
Basic Shell Script Structure:
#!/bin/bash
# System health check script - Linux version
echo "=== System Health Report $(date) ==="
# Check disk space
echo "Disk Usage:"
df -h | grep -v tmpfs
# Check memory
echo -e "\nMemory Usage:"
free -h
# Check CPU load
echo -e "\nSystem Load:"
uptime
# Check for failed services
echo -e "\nFailed Services:"
systemctl list-units --failed
# Check last 10 system errors
echo -e "\nRecent Errors:"
journalctl -p err -n 10 --no-pager
echo "=== Health Check Complete ==="
Advanced Business Backup Script:
#!/bin/bash
# Comprehensive backup script for business data
# Configuration
BACKUP_BASE="/backup"
DATE=$(date +%Y%m%d_%H%M%S)
RETENTION_DAYS=30
LOG_FILE="/var/log/business_backup.log"
EMAIL_ALERT="admin@company.com"
# Function to log messages
log_message() {
echo "$(date '+%Y-%m-%d %H:%M:%S'): $1" | tee -a "$LOG_FILE"
}
# Function to send alerts
send_alert() {
echo "$1" | mail -s "Backup Alert - $(hostname)" "$EMAIL_ALERT"
}
# Create backup directory
BACKUP_DIR="$BACKUP_BASE/$(date +%Y%m%d)"
mkdir -p "$BACKUP_DIR"
log_message "Starting backup to $BACKUP_DIR"
# Backup databases
log_message "Backing up databases..."
mysqldump -u backup_user -p'backup_password' --all-databases > "$BACKUP_DIR/all_databases.sql"
if [ $? -eq 0 ]; then
log_message "Database backup completed successfully"
else
log_message "ERROR: Database backup failed"
send_alert "Database backup failed on $(hostname)"
exit 1
fi
# Backup web files
log_message "Backing up web files..."
tar -czf "$BACKUP_DIR/web_files.tar.gz" /var/www/
if [ $? -eq 0 ]; then
log_message "Web files backup completed successfully"
else
log_message "ERROR: Web files backup failed"
send_alert "Web files backup failed on $(hostname)"
fi
# Backup user home directories
log_message "Backing up user home directories..."
tar -czf "$BACKUP_DIR/home_directories.tar.gz" /home/
if [ $? -eq 0 ]; then
log_message "Home directories backup completed successfully"
else
log_message "ERROR: Home directories backup failed"
send_alert "Home directories backup failed on $(hostname)"
fi
# Clean up old backups
log_message "Cleaning up backups older than $RETENTION_DAYS days..."
find "$BACKUP_BASE" -type d -mtime +$RETENTION_DAYS -exec rm -rf {} \;
# Verify backup integrity
log_message "Verifying backup integrity..."
BACKUP_SIZE=$(du -sh "$BACKUP_DIR" | cut -f1)
FILE_COUNT=$(find "$BACKUP_DIR" -type f | wc -l)
log_message "Backup completed: Size=$BACKUP_SIZE, Files=$FILE_COUNT"
send_alert "Backup completed successfully on $(hostname): Size=$BACKUP_SIZE, Files=$FILE_COUNT"
Advanced Troubleshooting Techniques
Systematic Problem-Solving Approach
The OSI Model for Command Line Troubleshooting:
Layer 7 - Application: Check application logs and processes
Layer 6 - Presentation: Verify data formats and encryption
Layer 5 - Session: Test login sessions and connections
Layer 4 - Transport: Check port connectivity and services
Layer 3 - Network: Verify IP connectivity and routing
Layer 2 - Data Link: Check network interfaces and switches
Layer 1 - Physical: Verify cables and hardware status
Network Troubleshooting Toolkit
# Connectivity testing
ping -c 4 8.8.8.8 # Test basic connectivity
traceroute google.com # Show route to destination
nslookup google.com # Test DNS resolution
dig google.com # Advanced DNS lookup
# Port and service testing
telnet server 80 # Test port connectivity
nc -zv server 22 # Test SSH port
curl -I http://website.com # Test web server response
nmap -p 22,80,443 server # Scan multiple ports
# Network interface diagnostics
ip link show # Show network interfaces
ethtool eth0 # Show interface details
ss -tulpn # Show listening services
Log Analysis and Monitoring
# Real-time log monitoring
tail -f /var/log/syslog | grep -i error # Follow error logs
tail -f /var/log/apache2/error.log # Monitor web server errors
journalctl -f -u mysql # Follow MySQL service logs
# Log analysis and statistics
awk '/Failed password/ {print $11}' /var/log/auth.log | sort | uniq -c | sort -nr
grep "$(date '+%b %d')" /var/log/syslog | grep -i error | wc -l
zgrep "ERROR" /var/log/apache2/error.log* | wc -l
# Performance monitoring commands
iostat -x 1 # Disk I/O statistics
vmstat 1 # Virtual memory statistics
sar -u 1 10 # CPU utilization over time
Hands-on Activity: Command Line Productivity
Time: 35 minutes
Objective
Master essential command line tasks for system administration
Part A: Windows Command Line (15 minutes)
-
System Information Gathering:
REM Open Command Prompt as Administrator
systeminfo > system_report.txt
ipconfig /all >> system_report.txt
tasklist >> system_report.txt
type system_report.txt | find "Total Physical Memory" -
User Management with PowerShell:
# Open PowerShell as Administrator
Get-LocalUser # List current users
New-LocalUser -Name "testuser" -Description "Test Account" -Password (ConvertTo-SecureString "TempPass123!" -AsPlainText -Force)
Get-LocalUser testuser # Verify user creation
Remove-LocalUser testuser # Clean up test user -
Simple Automation: Create a batch file called
daily_info.bat:@echo off
echo Daily System Report - %date%
echo ================================
echo.
echo Current Users:
query user 2>nul || echo No users currently logged in
echo.
echo Disk Space:
for /f "tokens=1,2,3,4" %%a in ('dir C:\ /-c ^| find "bytes free"') do echo %%a %%b %%c %%d
echo.
echo Running Services:
sc query state= all | find "SERVICE_NAME" | find /c "SERVICE_NAME"
echo services are currently running
pause
Part B: Linux Command Mastery (20 minutes)
-
Log Analysis Practice:
# View system logs
sudo tail -20 /var/log/syslog
# Search for specific events
grep -i "error\|fail\|warn" /var/log/syslog | tail -10
# Count different types of log entries
grep -c "INFO" /var/log/syslog
grep -c "ERROR" /var/log/syslog
# Analyze authentication attempts
grep "authentication failure" /var/log/auth.log | tail -5 -
System Monitoring:
# Check system resources
free -h # Memory usage
df -h # Disk usage
ps aux | head -20 # Running processes
# Network information
ip addr show # Network interfaces
ss -tuln | grep :22 # SSH service listening
netstat -i # Network interface statistics -
Create System Health Script: Create file
health_check.sh:#!/bin/bash
echo "=== Quick System Health Check ==="
echo "Date: $(date)"
echo
echo "Uptime:"
uptime
echo
echo "Disk Usage (>80% warning):"
df -h | awk '$5 > 80 {print $0 " - WARNING: Disk space low"}'
df -h | awk '$5 <= 80 {print $0}'
echo
echo "Memory Usage:"
free -h
echo
echo "Load Average:"
cat /