Code Snippets

A collection of useful code snippets, commands, and examples I've found helpful in my work.

Showing 39 of 39 snippets

Search multiple log files for error patterns

#!/bin/bash

# Enterprise log error detection script
# Searches multiple log files for common error patterns

LOG_DIR=${1:-/var/log}
SEARCH_PATTERNS=(
    "ERROR"
    "FATAL"
    "CRITICAL"
    "Exception"
    "Failed"
    "denied"
    "timeout"
    "connection refused"
)
OUTPUT_FILE="error_report_$(date +%Y%m%d_%H%M%S).txt"

find_errors() {
    local log_file=$1
    local pattern=$2
    
    if [ -f "$log_file" ] && [ -r "$log_file" ]; then
        grep -i "$pattern" "$log_file" 2>/dev/null | while read -r line; do
            echo "[$pattern] $log_file: $line"
        done
    fi
}

{
    echo "=== Error Log Analysis ==="
    echo "Search directory: $LOG_DIR"
    echo "Analysis date: $(date)"
    echo "Patterns searched: ${SEARCH_PATTERNS[*]}"
    echo ""
    
    # Find all log files
    LOG_FILES=$(find "$LOG_DIR" -type f \( -name "*.log" -o -name "*.log.*" \) 2>/dev/null)
    
    if [ -z "$LOG_FILES" ]; then
        echo "No log files found in $LOG_DIR"
        exit 1
    fi
    
    echo "Found $(echo "$LOG_FILES" | wc -l) log files"
    echo ""
    
    # Search each pattern in each log file
    for pattern in "${SEARCH_PATTERNS[@]}"; do
        echo "=== Searching for: $pattern ==="
        echo ""
        
        for log_file in $LOG_FILES; do
            find_errors "$log_file" "$pattern"
        done
        
        echo ""
    done
    
    # Summary by log file
    echo "=== Error Count by Log File ==="
    for log_file in $LOG_FILES; do
        if [ -f "$log_file" ] && [ -r "$log_file" ]; then
            ERROR_COUNT=0
            for pattern in "${SEARCH_PATTERNS[@]}"; do
                COUNT=$(grep -ic "$pattern" "$log_file" 2>/dev/null || echo 0)
                ERROR_COUNT=$((ERROR_COUNT + COUNT))
            done
            if [ $ERROR_COUNT -gt 0 ]; then
                echo "$log_file: $ERROR_COUNT errors found"
            fi
        fi
    done
    echo ""
    
    # Recent errors (last 100 lines of each log)
    echo "=== Recent Errors (Last 100 lines) ==="
    for log_file in $LOG_FILES; do
        if [ -f "$log_file" ] && [ -r "$log_file" ]; then
            RECENT_ERRORS=$(tail -100 "$log_file" 2>/dev/null | grep -iE "$(IFS='|'; echo "${SEARCH_PATTERNS[*]}")" | wc -l)
            if [ $RECENT_ERRORS -gt 0 ]; then
                echo ""
                echo "--- $log_file (last 100 lines) ---"
                tail -100 "$log_file" 2>/dev/null | grep -iE "$(IFS='|'; echo "${SEARCH_PATTERNS[*]}")"
            fi
        fi
    done
    
} | tee "$OUTPUT_FILE"

echo ""
echo "Error analysis complete. Results saved to: $OUTPUT_FILE"

Quick error search commands:

# Search for errors in a single log
grep -i error /var/log/syslog

# Search multiple patterns
grep -iE "error|fatal|critical" /var/log/app.log

# Search with context (lines before/after)
grep -i error -A 5 -B 5 /var/log/app.log

# Count errors
grep -ic error /var/log/app.log

# Find errors in last hour
tail -1000 /var/log/app.log | grep -i error

# Search all log files in directory
grep -r "error" /var/log/
BashLog AnalysisTroubleshootingError Detection

Analyze Apache access logs for common patterns and issues

#!/bin/bash

# Enterprise Apache log analysis script
# Parses access logs for common patterns, errors, and statistics

LOG_FILE=${1:-/var/log/apache2/access.log}
OUTPUT_FILE="apache_analysis_$(date +%Y%m%d_%H%M%S).txt"

if [ ! -f "$LOG_FILE" ]; then
    echo "Error: Log file not found: $LOG_FILE"
    exit 1
fi

{
    echo "=== Apache Access Log Analysis ==="
    echo "Log file: $LOG_FILE"
    echo "Analysis date: $(date)"
    echo "Total log entries: $(wc -l < "$LOG_FILE")"
    echo ""
    
    echo "=== Top 10 IP Addresses ==="
    awk '{print $1}' "$LOG_FILE" | sort | uniq -c | sort -rn | head -10
    echo ""
    
    echo "=== Top 10 Requested URLs ==="
    awk '{print $7}' "$LOG_FILE" | sort | uniq -c | sort -rn | head -10
    echo ""
    
    echo "=== HTTP Status Codes ==="
    awk '{print $9}' "$LOG_FILE" | sort | uniq -c | sort -rn
    echo ""
    
    echo "=== Error Responses (4xx, 5xx) ==="
    awk '$9 >= 400 {print $9, $7, $1}' "$LOG_FILE" | sort | uniq -c | sort -rn | head -20
    echo ""
    
    echo "=== Top User Agents ==="
    awk -F'"' '{print $6}' "$LOG_FILE" | sort | uniq -c | sort -rn | head -10
    echo ""
    
    echo "=== Requests by Hour ==="
    awk '{print $4}' "$LOG_FILE" | cut -d: -f2 | sort | uniq -c | sort -n
    echo ""
    
    echo "=== Most Active Hours ==="
    awk '{print $4}' "$LOG_FILE" | cut -d: -f2 | sort | uniq -c | sort -rn | head -10
    echo ""
    
    echo "=== Bandwidth Usage (Top 10) ==="
    awk '{sum[$7] += $10} END {for (url in sum) print sum[url], url}' "$LOG_FILE" | sort -rn | head -10
    echo ""
    
    echo "=== Suspicious Activity (Multiple 404s from same IP) ==="
    awk '$9 == 404 {print $1, $7}' "$LOG_FILE" | sort | uniq -c | sort -rn | head -10
    echo ""
    
    echo "=== Requests by Method ==="
    awk '{print $6}' "$LOG_FILE" | sed 's/"//g' | sort | uniq -c | sort -rn
    echo ""
    
} | tee "$OUTPUT_FILE"

echo ""
echo "Analysis complete. Results saved to: $OUTPUT_FILE"

Quick log analysis commands:

# Count total requests
wc -l /var/log/apache2/access.log

# Find most common IPs
awk '{print $1}' access.log | sort | uniq -c | sort -rn | head -10

# Find 404 errors
grep " 404 " access.log

# Find requests in last hour
tail -1000 access.log | grep "$(date +%d/%b/%Y:%H)"

# Real-time log monitoring
tail -f /var/log/apache2/access.log
BashLog AnalysisApacheWeb Server

Identify all listening ports and associated processes

#!/bin/bash

# Enterprise port scanning script
# Lists all listening ports with process information

echo "=== Listening Ports and Processes ==="
echo "Generated: $(date)"
echo ""

# Method 1: Using ss (modern, faster)
if command -v ss &> /dev/null; then
    echo "Using 'ss' command:"
    echo "-------------------"
    ss -tulnp | grep LISTEN | while read line; do
        PROTO=$(echo $line | awk '{print $1}')
        STATE=$(echo $line | awk '{print $2}')
        LOCAL=$(echo $line | awk '{print $5}')
        PROCESS=$(echo $line | awk '{print $7}')
        echo "Protocol: $PROTO | State: $STATE | Address: $LOCAL | Process: $PROCESS"
    done
    echo ""
fi

# Method 2: Using netstat (fallback)
if command -v netstat &> /dev/null; then
    echo "Using 'netstat' command:"
    echo "-------------------------"
    netstat -tulnp 2>/dev/null | grep LISTEN | while read line; do
        echo "$line"
    done
    echo ""
fi

# Detailed process information
echo "=== Detailed Process Information ==="
echo ""

# Get unique PIDs from listening ports
PIDS=$(ss -tulnp 2>/dev/null | grep LISTEN | grep -oP 'pid=\K[0-9]+' | sort -u)

if [ -z "$PIDS" ]; then
    PIDS=$(netstat -tulnp 2>/dev/null | grep LISTEN | awk '{print $7}' | cut -d'/' -f1 | grep -E '^[0-9]+$' | sort -u)
fi

for PID in $PIDS; do
    if [ -d "/proc/$PID" ]; then
        echo "PID: $PID"
        echo "  Command: $(cat /proc/$PID/comm 2>/dev/null)"
        echo "  Full Command: $(cat /proc/$PID/cmdline 2>/dev/null | tr '\0' ' ')"
        echo "  User: $(stat -c '%U' /proc/$PID 2>/dev/null)"
        echo "  Ports:"
        ss -tulnp 2>/dev/null | grep "pid=$PID" | awk '{print "    - " $5}'
        echo ""
    fi
done

# Summary by port number
echo "=== Summary by Port Number ==="
ss -tulnp 2>/dev/null | grep LISTEN | awk '{print $5}' | cut -d':' -f2 | sort -n | uniq -c | sort -rn | head -20

Quick port checks:

# List all listening ports
ss -tuln
netstat -tuln

# Find what's using a specific port
lsof -i :80
ss -tulnp | grep :80

# Find process by port
fuser 80/tcp

# Check if port is in use
netstat -tuln | grep :22 && echo "Port 22 is in use" || echo "Port 22 is free"
BashNetworkingSecurityProcess Management

Comprehensive network connectivity testing with logging

#!/bin/bash

# Enterprise network connectivity testing script
# Tests connectivity to multiple hosts with detailed logging

HOSTS_FILE=${1:-hosts.txt}
LOG_FILE="connectivity_test_$(date +%Y%m%d_%H%M%S).log"
TIMEOUT=${2:-5}

if [ ! -f "$HOSTS_FILE" ]; then
    echo "Creating sample hosts file: $HOSTS_FILE"
    cat > "$HOSTS_FILE" << EOF
8.8.8.8
google.com
github.com
EOF
fi

log_result() {
    echo "$(date '+%Y-%m-%d %H:%M:%S') - $1" | tee -a "$LOG_FILE"
}

test_host() {
    local host=$1
    local port=${2:-80}
    
    log_result "Testing $host:$port..."
    
    # Test ICMP ping
    if ping -c 1 -W $TIMEOUT "$host" > /dev/null 2>&1; then
        PING_RESULT="✓ Ping OK"
    else
        PING_RESULT="✗ Ping FAILED"
    fi
    
    # Test TCP port
    if timeout $TIMEOUT bash -c "echo > /dev/tcp/$host/$port" 2>/dev/null; then
        PORT_RESULT="✓ Port $port OPEN"
    else
        PORT_RESULT="✗ Port $port CLOSED/UNREACHABLE"
    fi
    
    # DNS resolution test
    if host "$host" > /dev/null 2>&1; then
        DNS_RESULT="✓ DNS resolves"
        IP=$(host "$host" | grep "has address" | head -1 | awk '{print $4}')
    else
        DNS_RESULT="✗ DNS FAILED"
        IP="N/A"
    fi
    
    # Traceroute (first 5 hops)
    log_result "  $PING_RESULT"
    log_result "  $PORT_RESULT"
    log_result "  $DNS_RESULT"
    log_result "  IP: $IP"
    
    if [ "$PING_RESULT" = "✓ Ping OK" ]; then
        log_result "  Traceroute (first 5 hops):"
        traceroute -m 5 "$host" 2>/dev/null | head -6 | sed 's/^/    /' | tee -a "$LOG_FILE"
    fi
    
    log_result ""
}

log_result "=== Network Connectivity Test ==="
log_result "Started: $(date)"
log_result "Hosts file: $HOSTS_FILE"
log_result "Timeout: ${TIMEOUT}s"
log_result ""

while IFS= read -r line || [ -n "$line" ]; do
    # Skip comments and empty lines
    [[ "$line" =~ ^#.*$ ]] && continue
    [[ -z "$line" ]] && continue
    
    # Parse host:port format
    if [[ "$line" =~ : ]]; then
        HOST=$(echo "$line" | cut -d: -f1)
        PORT=$(echo "$line" | cut -d: -f2)
    else
        HOST="$line"
        PORT=80
    fi
    
    test_host "$HOST" "$PORT"
done < "$HOSTS_FILE"

log_result "=== Test Complete ==="
log_result "Results saved to: $LOG_FILE"

Quick connectivity tests:

# Test single host
ping -c 4 google.com

# Test TCP port
timeout 5 bash -c "echo > /dev/tcp/google.com/80" && echo "Port open" || echo "Port closed"

# Test multiple ports
for port in 22 80 443; do
    timeout 2 bash -c "echo > /dev/tcp/hostname/$port" 2>/dev/null && echo "Port $port: OPEN" || echo "Port $port: CLOSED"
done

# DNS lookup
nslookup google.com
dig google.com
BashNetworkingTroubleshootingConnectivity

Create timestamped backups with rotation and error handling

#!/bin/bash

# Enterprise directory backup script
# Creates timestamped backups with rotation and validation

SOURCE_DIR=$1
BACKUP_BASE_DIR=${2:-/backups}
RETENTION_DAYS=${3:-30}

if [ -z "$SOURCE_DIR" ] || [ ! -d "$SOURCE_DIR" ]; then
    echo "Usage: $0 <source_directory> [backup_base_dir] [retention_days]"
    echo "Example: $0 /var/www /backups 30"
    exit 1
fi

TIMESTAMP=$(date +%Y%m%d_%H%M%S)
BACKUP_NAME=$(basename "$SOURCE_DIR")
BACKUP_DIR="$BACKUP_BASE_DIR/$BACKUP_NAME"
BACKUP_FILE="$BACKUP_DIR/${BACKUP_NAME}_${TIMESTAMP}.tar.gz"
LOG_FILE="$BACKUP_DIR/backup.log"

# Create backup directory if it doesn't exist
mkdir -p "$BACKUP_DIR"

log_message() {
    echo "$(date '+%Y-%m-%d %H:%M:%S') - $1" | tee -a "$LOG_FILE"
}

# Create backup
log_message "Starting backup of $SOURCE_DIR"
tar -czf "$BACKUP_FILE" -C "$(dirname "$SOURCE_DIR")" "$(basename "$SOURCE_DIR")" 2>&1 | tee -a "$LOG_FILE"

if [ ${PIPESTATUS[0]} -eq 0 ]; then
    BACKUP_SIZE=$(du -h "$BACKUP_FILE" | cut -f1)
    log_message "Backup completed successfully: $BACKUP_FILE ($BACKUP_SIZE)"
    
    # Verify backup integrity
    if tar -tzf "$BACKUP_FILE" > /dev/null 2>&1; then
        log_message "Backup integrity verified"
    else
        log_message "ERROR: Backup integrity check failed"
        exit 1
    fi
else
    log_message "ERROR: Backup failed"
    rm -f "$BACKUP_FILE"
    exit 1
fi

# Clean up old backups
log_message "Cleaning up backups older than $RETENTION_DAYS days"
find "$BACKUP_DIR" -name "${BACKUP_NAME}_*.tar.gz" -type f -mtime +$RETENTION_DAYS -delete
find "$BACKUP_DIR" -name "${BACKUP_NAME}_*.tar.gz" -type f -mtime +$RETENTION_DAYS -exec log_message "Deleted old backup: {}" \;

Quick backup commands:

# Simple tar backup
tar -czf backup_$(date +%Y%m%d).tar.gz /path/to/directory

# Backup with rsync (preserves permissions, faster for large dirs)
rsync -avz --delete /source/ /backup/destination/

# Incremental backup with rsync
rsync -avz --link-dest=/backup/latest /source/ /backup/$(date +%Y%m%d)/
BashSystem AdministrationBackupFile Management

Monitor disk usage and alert when thresholds are exceeded

#!/bin/bash

# Enterprise disk space monitoring script
# Checks disk usage and alerts when thresholds are exceeded

THRESHOLD_WARNING=80  # Percentage for warning
THRESHOLD_CRITICAL=90  # Percentage for critical alert
LOG_FILE="/var/log/disk-monitor.log"

# Function to log messages
log_message() {
    echo "$(date '+%Y-%m-%d %H:%M:%S') - $1" >> "$LOG_FILE"
}

# Function to send alert (customize based on your alerting system)
send_alert() {
    local level=$1
    local message=$2
    log_message "[$level] $message"
    # Example: Send email or use monitoring system API
    # mail -s "Disk Space Alert: $level" [email protected] <<< "$message"
}

# Check all mounted filesystems
df -h | awk 'NR>1 {print $5, $6}' | while read usage mountpoint; do
    # Remove % sign and get numeric value
    usage_num=$(echo $usage | sed 's/%//')
    
    if [ "$usage_num" -ge "$THRESHOLD_CRITICAL" ]; then
        send_alert "CRITICAL" "Disk space critical on $mountpoint: ${usage} used"
    elif [ "$usage_num" -ge "$THRESHOLD_WARNING" ]; then
        send_alert "WARNING" "Disk space warning on $mountpoint: ${usage} used"
    fi
done

# Find largest files/directories (top 10)
echo "Top 10 largest directories:" >> "$LOG_FILE"
du -h / 2>/dev/null | sort -rh | head -10 >> "$LOG_FILE"

Quick check for specific mount point:

# Check specific mount point
df -h /var | awk 'NR==2 {print $5}'

# Find largest files in a directory
du -h /path/to/directory | sort -rh | head -20
BashSystem AdministrationMonitoringDisk Management

Safely find and terminate processes by name with error handling

#!/bin/bash

# Enterprise process termination script
# Safely kills processes by name with validation and logging

PROCESS_NAME=$1
SIGNAL=${2:-TERM}  # Default to TERM signal, can use KILL for force

if [ -z "$PROCESS_NAME" ]; then
    echo "Usage: $0 <process_name> [SIGNAL]"
    echo "Example: $0 nginx TERM"
    exit 1
fi

LOG_FILE="/var/log/process-kill.log"

log_action() {
    echo "$(date '+%Y-%m-%d %H:%M:%S') - $1" >> "$LOG_FILE"
}

# Find PIDs for the process
PIDS=$(pgrep -f "$PROCESS_NAME")

if [ -z "$PIDS" ]; then
    echo "No processes found matching: $PROCESS_NAME"
    exit 0
fi

echo "Found processes matching '$PROCESS_NAME':"
ps -p $PIDS -o pid,user,cmd

read -p "Kill these processes? (yes/no): " confirm

if [ "$confirm" != "yes" ]; then
    echo "Aborted."
    exit 0
fi

# Kill processes
for PID in $PIDS; do
    log_action "Killing PID $PID (process: $PROCESS_NAME) with signal $SIGNAL"
    kill -$SIGNAL $PID 2>/dev/null
    
    if [ $? -eq 0 ]; then
        echo "Successfully sent $SIGNAL signal to PID $PID"
    else
        echo "Failed to kill PID $PID" >&2
        log_action "ERROR: Failed to kill PID $PID"
    fi
done

# Wait and verify
sleep 2
REMAINING=$(pgrep -f "$PROCESS_NAME")
if [ -n "$REMAINING" ]; then
    echo "Warning: Some processes are still running. PIDs: $REMAINING"
    log_action "WARNING: Processes still running after kill: $REMAINING"
fi

Quick one-liner version:

# Kill all processes matching name (use with caution)
pkill -f "process_name"

# Force kill if TERM doesn't work
pkill -9 -f "process_name"

# Kill specific PID
kill -TERM <PID>
BashSystem AdministrationProcess Management

Gather comprehensive system information for troubleshooting

#!/bin/bash

# Enterprise system information gathering script
# Collects comprehensive system details for troubleshooting

OUTPUT_FILE="${1:-system_info_$(hostname)_$(date +%Y%m%d_%H%M%S).txt}"

{
    echo "=========================================="
    echo "System Information Report"
    echo "Generated: $(date)"
    echo "Hostname: $(hostname)"
    echo "=========================================="
    echo ""
    
    echo "=== Operating System ==="
    if [ -f /etc/os-release ]; then
        cat /etc/os-release
    elif [ -f /etc/redhat-release ]; then
        cat /etc/redhat-release
    elif [ -f /etc/debian_version ]; then
        echo "Debian $(cat /etc/debian_version)"
    fi
    uname -a
    echo ""
    
    echo "=== CPU Information ==="
    lscpu 2>/dev/null || cat /proc/cpuinfo | grep -E "model name|processor|cores"
    echo ""
    
    echo "=== Memory Information ==="
    free -h
    echo ""
    echo "Memory Details:"
    cat /proc/meminfo | head -10
    echo ""
    
    echo "=== Disk Usage ==="
    df -h
    echo ""
    
    echo "=== Network Interfaces ==="
    ip addr show 2>/dev/null || ifconfig
    echo ""
    
    echo "=== Network Connections ==="
    ss -tuln 2>/dev/null || netstat -tuln
    echo ""
    
    echo "=== Running Services ==="
    systemctl list-units --type=service --state=running 2>/dev/null | head -20
    echo ""
    
    echo "=== Top Processes by CPU ==="
    ps aux --sort=-%cpu | head -10
    echo ""
    
    echo "=== Top Processes by Memory ==="
    ps aux --sort=-%mem | head -10
    echo ""
    
    echo "=== Load Average ==="
    uptime
    echo ""
    
    echo "=== Kernel Modules ==="
    lsmod | head -20
    echo ""
    
    echo "=== Mounted Filesystems ==="
    mount | column -t
    echo ""
    
    echo "=== Environment Variables ==="
    env | sort
    echo ""
    
    echo "=== Last Boot Time ==="
    who -b 2>/dev/null || last reboot | head -1
    echo ""
    
} | tee "$OUTPUT_FILE"

echo "System information saved to: $OUTPUT_FILE"

Quick system checks:

# Quick system overview
echo "Uptime: $(uptime)"
echo "Load: $(cat /proc/loadavg)"
echo "Memory: $(free -h | grep Mem)"
echo "Disk: $(df -h / | tail -1)"

# Check specific resource
free -h          # Memory
df -h            # Disk
top -bn1 | head  # CPU processes
BashSystem AdministrationMonitoringTroubleshooting

Backup and restore MySQL databases with mysqldump and other tools

#!/bin/bash

# MySQL Backup and Restore Script
# Enterprise backup with compression, rotation, and validation

MYSQL_USER="backup_user"
MYSQL_PASS="password"
MYSQL_HOST="localhost"
BACKUP_DIR="/backups/mysql"
RETENTION_DAYS=30
TIMESTAMP=$(date +%Y%m%d_%H%M%S)

# Create backup directory
mkdir -p "$BACKUP_DIR"

backup_database() {
    local db_name=$1
    local backup_file="$BACKUP_DIR/${db_name}_${TIMESTAMP}.sql.gz"
    
    echo "Backing up database: $db_name"
    
    # Full backup with compression
    mysqldump -u "$MYSQL_USER" -p"$MYSQL_PASS" -h "$MYSQL_HOST" \
        --single-transaction \
        --routines \
        --triggers \
        --events \
        --quick \
        --lock-tables=false \
        "$db_name" | gzip > "$backup_file"
    
    if [ ${PIPESTATUS[0]} -eq 0 ]; then
        echo "Backup completed: $backup_file"
        echo "Size: $(du -h "$backup_file" | cut -f1)"
        
        # Verify backup integrity
        if gunzip -t "$backup_file" 2>/dev/null; then
            echo "Backup integrity verified"
        else
            echo "ERROR: Backup integrity check failed"
            rm -f "$backup_file"
            return 1
        fi
    else
        echo "ERROR: Backup failed"
        rm -f "$backup_file"
        return 1
    fi
}

backup_all_databases() {
    echo "Backing up all databases..."
    
    # Get list of databases (exclude system databases)
    databases=$(mysql -u "$MYSQL_USER" -p"$MYSQL_PASS" -h "$MYSQL_HOST" \
        -e "SHOW DATABASES;" | grep -Ev "(Database|information_schema|performance_schema|mysql|sys)")
    
    for db in $databases; do
        backup_database "$db"
    done
}

restore_database() {
    local db_name=$1
    local backup_file=$2
    
    if [ ! -f "$backup_file" ]; then
        echo "Error: Backup file not found: $backup_file"
        return 1
    fi
    
    echo "Restoring database: $db_name from $backup_file"
    
    # Create database if it doesn't exist
    mysql -u "$MYSQL_USER" -p"$MYSQL_PASS" -h "$MYSQL_HOST" \
        -e "CREATE DATABASE IF NOT EXISTS $db_name;"
    
    # Restore database
    if [[ "$backup_file" == *.gz ]]; then
        gunzip < "$backup_file" | mysql -u "$MYSQL_USER" -p"$MYSQL_PASS" -h "$MYSQL_HOST" "$db_name"
    else
        mysql -u "$MYSQL_USER" -p"$MYSQL_PASS" -h "$MYSQL_HOST" "$db_name" < "$backup_file"
    fi
    
    if [ $? -eq 0 ]; then
        echo "Database restored successfully"
    else
        echo "ERROR: Restore failed"
        return 1
    fi
}

cleanup_old_backups() {
    echo "Cleaning up backups older than $RETENTION_DAYS days..."
    find "$BACKUP_DIR" -name "*.sql.gz" -type f -mtime +$RETENTION_DAYS -delete
    echo "Cleanup completed"
}

# Main execution
ACTION=$1
DB_NAME=$2
BACKUP_FILE=$3

case $ACTION in
    backup)
        if [ -z "$DB_NAME" ]; then
            backup_all_databases
        else
            backup_database "$DB_NAME"
        fi
        cleanup_old_backups
        ;;
    restore)
        if [ -z "$DB_NAME" ] || [ -z "$BACKUP_FILE" ]; then
            echo "Usage: $0 restore <database_name> <backup_file>"
            exit 1
        fi
        restore_database "$DB_NAME" "$BACKUP_FILE"
        ;;
    *)
        echo "Usage: $0 <backup|restore> [database_name] [backup_file]"
        exit 1
        ;;
esac

Common backup commands:

# Backup single database
mysqldump -u user -p database_name > backup.sql

# Backup with compression
mysqldump -u user -p database_name | gzip > backup.sql.gz

# Backup all databases
mysqldump -u user -p --all-databases > all_databases.sql

# Backup specific tables
mysqldump -u user -p database_name table1 table2 > tables.sql

# Backup with single transaction (consistent backup)
mysqldump -u user -p --single-transaction database_name > backup.sql

# Backup structure only (no data)
mysqldump -u user -p --no-data database_name > structure.sql

# Backup data only (no structure)
mysqldump -u user -p --no-create-info database_name > data.sql

# Restore database
mysql -u user -p database_name < backup.sql

# Restore compressed backup
gunzip < backup.sql.gz | mysql -u user -p database_name

# Backup with specific options
mysqldump -u user -p \
    --single-transaction \
    --routines \
    --triggers \
    --events \
    --quick \
    --lock-tables=false \
    database_name > backup.sql
DatabaseMySQLBackupRestoremysqldump

Create and manage MySQL users, roles, and permissions

-- MySQL User and Permission Management
-- Enterprise security best practices

-- ============================================
-- CREATE USER
-- ============================================

-- Create user with password
CREATE USER 'db_user'@'localhost' IDENTIFIED BY 'StrongPassword123!';

-- Create user from any host
CREATE USER 'db_user'@'%' IDENTIFIED BY 'StrongPassword123!';

-- Create user from specific IP
CREATE USER 'db_user'@'192.168.1.100' IDENTIFIED BY 'StrongPassword123!';

-- Create user with password expiration
CREATE USER 'db_user'@'localhost' 
IDENTIFIED BY 'StrongPassword123!'
PASSWORD EXPIRE INTERVAL 90 DAY;

-- Create user with resource limits
CREATE USER 'db_user'@'localhost' 
IDENTIFIED BY 'StrongPassword123!'
WITH MAX_QUERIES_PER_HOUR 1000
     MAX_CONNECTIONS_PER_HOUR 100
     MAX_UPDATES_PER_HOUR 500;

-- ============================================
-- GRANT PERMISSIONS
-- ============================================

-- Grant all privileges on database
GRANT ALL PRIVILEGES ON database_name.* TO 'db_user'@'localhost';

-- Grant specific privileges
GRANT SELECT, INSERT, UPDATE, DELETE ON database_name.* TO 'db_user'@'localhost';

-- Grant privileges on specific table
GRANT SELECT, INSERT, UPDATE ON database_name.table_name TO 'db_user'@'localhost';

-- Grant privileges on all databases
GRANT SELECT ON *.* TO 'db_user'@'localhost';

-- Grant privileges with GRANT OPTION (allows user to grant to others)
GRANT SELECT, INSERT ON database_name.* TO 'db_user'@'localhost' WITH GRANT OPTION;

-- Grant specific column privileges
GRANT SELECT (column1, column2), UPDATE (column1) ON database_name.table_name TO 'db_user'@'localhost';

-- Grant procedure/function privileges
GRANT EXECUTE ON PROCEDURE database_name.procedure_name TO 'db_user'@'localhost';

-- ============================================
-- ROLES (MySQL 8.0+)
-- ============================================

-- Create role
CREATE ROLE 'readonly_role', 'readwrite_role';

-- Grant privileges to role
GRANT SELECT ON database_name.* TO 'readonly_role';
GRANT SELECT, INSERT, UPDATE, DELETE ON database_name.* TO 'readwrite_role';

-- Grant role to user
GRANT 'readonly_role' TO 'db_user'@'localhost';

-- Set default role
SET DEFAULT ROLE 'readonly_role' TO 'db_user'@'localhost';

-- Activate role for current session
SET ROLE 'readonly_role';

-- ============================================
-- REVOKE PERMISSIONS
-- ============================================

-- Revoke specific privileges
REVOKE INSERT, UPDATE ON database_name.* FROM 'db_user'@'localhost';

-- Revoke all privileges
REVOKE ALL PRIVILEGES ON database_name.* FROM 'db_user'@'localhost';

-- Revoke GRANT OPTION
REVOKE GRANT OPTION ON database_name.* FROM 'db_user'@'localhost';

-- ============================================
-- VIEW PERMISSIONS
-- ============================================

-- Show grants for user
SHOW GRANTS FOR 'db_user'@'localhost';

-- Show current user grants
SHOW GRANTS;

-- List all users
SELECT user, host FROM mysql.user;

-- List user privileges
SELECT * FROM mysql.user WHERE user = 'db_user';

-- List database privileges
SELECT * FROM mysql.db WHERE user = 'db_user';

-- List table privileges
SELECT * FROM mysql.tables_priv WHERE user = 'db_user';

-- ============================================
-- MODIFY USER
-- ============================================

-- Change password
ALTER USER 'db_user'@'localhost' IDENTIFIED BY 'NewPassword123!';

-- Change password and expire immediately
ALTER USER 'db_user'@'localhost' IDENTIFIED BY 'NewPassword123!' PASSWORD EXPIRE;

-- Lock/unlock account
ALTER USER 'db_user'@'localhost' ACCOUNT LOCK;
ALTER USER 'db_user'@'localhost' ACCOUNT UNLOCK;

-- Change resource limits
ALTER USER 'db_user'@'localhost'
WITH MAX_QUERIES_PER_HOUR 2000
     MAX_CONNECTIONS_PER_HOUR 200;

-- Rename user
RENAME USER 'old_user'@'localhost' TO 'new_user'@'localhost';

-- ============================================
-- REMOVE USER
-- ============================================

-- Drop user
DROP USER 'db_user'@'localhost';

-- Drop multiple users
DROP USER 'user1'@'localhost', 'user2'@'localhost';

-- ============================================
-- FLUSH PRIVILEGES
-- ============================================

-- Apply privilege changes immediately
FLUSH PRIVILEGES;

Bash script for user management:

#!/bin/bash

# MySQL User Management Script
MYSQL_USER="admin"
MYSQL_PASS="password"
MYSQL_HOST="localhost"
DB_NAME="database_name"
NEW_USER="db_user"
NEW_PASS="StrongPassword123!"

# Create user
mysql -u "$MYSQL_USER" -p"$MYSQL_PASS" -h "$MYSQL_HOST" << EOF
CREATE USER '$NEW_USER'@'localhost' IDENTIFIED BY '$NEW_PASS';
GRANT SELECT, INSERT, UPDATE, DELETE ON $DB_NAME.* TO '$NEW_USER'@'localhost';
FLUSH PRIVILEGES;
EOF

# Verify user
mysql -u "$MYSQL_USER" -p"$MYSQL_PASS" -h "$MYSQL_HOST" -e "SHOW GRANTS FOR '$NEW_USER'@'localhost';"
DatabaseMySQLSecurityUser ManagementPermissions

Backup and restore PostgreSQL databases with pg_dump and pg_restore

#!/bin/bash

# PostgreSQL Backup and Restore Script
# Enterprise backup with compression, rotation, and validation

PGUSER="backup_user"
PGHOST="localhost"
BACKUP_DIR="/backups/postgresql"
RETENTION_DAYS=30
TIMESTAMP=$(date +%Y%m%d_%H%M%S)

# Create backup directory
mkdir -p "$BACKUP_DIR"

backup_database() {
    local db_name=$1
    local backup_file="$BACKUP_DIR/${db_name}_${TIMESTAMP}.dump"
    
    echo "Backing up database: $db_name"
    
    # Custom format backup (compressed, allows selective restore)
    pg_dump -U "$PGUSER" -h "$PGHOST" \
        -Fc \
        -f "$backup_file" \
        "$db_name"
    
    if [ $? -eq 0 ]; then
        echo "Backup completed: $backup_file"
        echo "Size: $(du -h "$backup_file" | cut -f1)"
        
        # Verify backup
        if pg_restore -l "$backup_file" > /dev/null 2>&1; then
            echo "Backup integrity verified"
        else
            echo "ERROR: Backup integrity check failed"
            rm -f "$backup_file"
            return 1
        fi
    else
        echo "ERROR: Backup failed"
        rm -f "$backup_file"
        return 1
    fi
}

backup_all_databases() {
    echo "Backing up all databases..."
    
    # Get list of databases (exclude template databases)
    databases=$(psql -U "$PGUSER" -h "$PGHOST" -t -c \
        "SELECT datname FROM pg_database WHERE datistemplate = false AND datname != 'postgres';")
    
    for db in $databases; do
        db=$(echo $db | xargs)  # Trim whitespace
        if [ -n "$db" ]; then
            backup_database "$db"
        fi
    done
}

restore_database() {
    local db_name=$1
    local backup_file=$2
    
    if [ ! -f "$backup_file" ]; then
        echo "Error: Backup file not found: $backup_file"
        return 1
    fi
    
    echo "Restoring database: $db_name from $backup_file"
    
    # Drop and recreate database
    psql -U "$PGUSER" -h "$PGHOST" -c "DROP DATABASE IF EXISTS $db_name;"
    psql -U "$PGUSER" -h "$PGHOST" -c "CREATE DATABASE $db_name;"
    
    # Restore database
    if [[ "$backup_file" == *.dump ]] || [[ "$backup_file" == *.custom ]]; then
        # Custom format
        pg_restore -U "$PGUSER" -h "$PGHOST" -d "$db_name" "$backup_file"
    elif [[ "$backup_file" == *.sql.gz ]]; then
        # SQL format compressed
        gunzip < "$backup_file" | psql -U "$PGUSER" -h "$PGHOST" "$db_name"
    elif [[ "$backup_file" == *.sql ]]; then
        # SQL format
        psql -U "$PGUSER" -h "$PGHOST" "$db_name" < "$backup_file"
    else
        echo "Error: Unknown backup format"
        return 1
    fi
    
    if [ $? -eq 0 ]; then
        echo "Database restored successfully"
    else
        echo "ERROR: Restore failed"
        return 1
    fi
}

backup_globals() {
    local backup_file="$BACKUP_DIR/globals_${TIMESTAMP}.sql"
    
    echo "Backing up global objects (roles, tablespaces)..."
    
    pg_dumpall -U "$PGUSER" -h "$PGHOST" \
        --globals-only \
        -f "$backup_file"
    
    if [ $? -eq 0 ]; then
        echo "Global backup completed: $backup_file"
    else
        echo "ERROR: Global backup failed"
        rm -f "$backup_file"
        return 1
    fi
}

cleanup_old_backups() {
    echo "Cleaning up backups older than $RETENTION_DAYS days..."
    find "$BACKUP_DIR" -name "*.dump" -type f -mtime +$RETENTION_DAYS -delete
    find "$BACKUP_DIR" -name "*.sql" -type f -mtime +$RETENTION_DAYS -delete
    find "$BACKUP_DIR" -name "*.sql.gz" -type f -mtime +$RETENTION_DAYS -delete
    echo "Cleanup completed"
}

# Main execution
ACTION=$1
DB_NAME=$2
BACKUP_FILE=$3

case $ACTION in
    backup)
        if [ -z "$DB_NAME" ]; then
            backup_globals
            backup_all_databases
        else
            backup_database "$DB_NAME"
        fi
        cleanup_old_backups
        ;;
    restore)
        if [ -z "$DB_NAME" ] || [ -z "$BACKUP_FILE" ]; then
            echo "Usage: $0 restore <database_name> <backup_file>"
            exit 1
        fi
        restore_database "$DB_NAME" "$BACKUP_FILE"
        ;;
    *)
        echo "Usage: $0 <backup|restore> [database_name] [backup_file]"
        exit 1
        ;;
esac

Common backup commands:

# Backup single database (custom format - compressed)
pg_dump -U user -h host -Fc database_name > backup.dump

# Backup single database (SQL format)
pg_dump -U user -h host database_name > backup.sql

# Backup with compression
pg_dump -U user -h host database_name | gzip > backup.sql.gz

# Backup all databases
pg_dumpall -U user -h host > all_databases.sql

# Backup global objects only (roles, tablespaces)
pg_dumpall -U user -h host --globals-only > globals.sql

# Backup schema only
pg_dump -U user -h host -s database_name > schema.sql

# Backup data only
pg_dump -U user -h host -a database_name > data.sql

# Restore custom format backup
pg_restore -U user -h host -d database_name backup.dump

# Restore SQL backup
psql -U user -h host database_name < backup.sql

# Restore compressed SQL backup
gunzip < backup.sql.gz | psql -U user -h host database_name

# Restore specific schema
pg_restore -U user -h host -d database_name -n schema_name backup.dump

# List contents of custom format backup
pg_restore -l backup.dump
DatabasePostgreSQLBackupRestorepg_dump

Create and manage PostgreSQL users, roles, and permissions

-- PostgreSQL User and Role Management
-- Enterprise security best practices

-- ============================================
-- CREATE ROLE/USER
-- ============================================

-- Create role (can be used as user or group)
CREATE ROLE role_name;

-- Create user (automatically has LOGIN privilege)
CREATE USER user_name WITH PASSWORD 'StrongPassword123!';

-- Create user with additional options
CREATE USER user_name WITH
    PASSWORD 'StrongPassword123!'
    CREATEDB
    CREATEROLE
    LOGIN
    VALID UNTIL '2025-12-31';

-- Create role with connection limit
CREATE ROLE user_name WITH
    PASSWORD 'StrongPassword123!'
    LOGIN
    CONNECTION LIMIT 10;

-- ============================================
-- GRANT PRIVILEGES
-- ============================================

-- Grant database privileges
GRANT CONNECT ON DATABASE database_name TO user_name;
GRANT CREATE ON DATABASE database_name TO user_name;

-- Grant schema privileges
GRANT USAGE ON SCHEMA schema_name TO user_name;
GRANT CREATE ON SCHEMA schema_name TO user_name;
GRANT ALL ON SCHEMA schema_name TO user_name;

-- Grant table privileges
GRANT SELECT, INSERT, UPDATE, DELETE ON TABLE schema_name.table_name TO user_name;
GRANT ALL PRIVILEGES ON TABLE schema_name.table_name TO user_name;

-- Grant privileges on all tables in schema
GRANT SELECT, INSERT, UPDATE, DELETE ON ALL TABLES IN SCHEMA schema_name TO user_name;

-- Grant sequence privileges
GRANT USAGE, SELECT ON SEQUENCE schema_name.sequence_name TO user_name;
GRANT ALL PRIVILEGES ON ALL SEQUENCES IN SCHEMA schema_name TO user_name;

-- Grant function/procedure privileges
GRANT EXECUTE ON FUNCTION schema_name.function_name TO user_name;
GRANT EXECUTE ON ALL FUNCTIONS IN SCHEMA schema_name TO user_name;

-- Grant default privileges (for future objects)
ALTER DEFAULT PRIVILEGES IN SCHEMA schema_name
    GRANT SELECT, INSERT, UPDATE, DELETE ON TABLES TO user_name;

ALTER DEFAULT PRIVILEGES IN SCHEMA schema_name
    GRANT USAGE, SELECT ON SEQUENCES TO user_name;

-- ============================================
-- ROLE MEMBERSHIP
-- ============================================

-- Grant role to user
GRANT role_name TO user_name;

-- Create role hierarchy
CREATE ROLE admin_role;
CREATE ROLE manager_role;
GRANT admin_role TO manager_role;
GRANT manager_role TO user_name;

-- ============================================
-- REVOKE PRIVILEGES
-- ============================================

-- Revoke specific privileges
REVOKE INSERT, UPDATE ON TABLE schema_name.table_name FROM user_name;

-- Revoke all privileges
REVOKE ALL PRIVILEGES ON TABLE schema_name.table_name FROM user_name;

-- Revoke role membership
REVOKE role_name FROM user_name;

-- ============================================
-- VIEW PERMISSIONS
-- ============================================

-- List all roles
SELECT rolname, rolsuper, rolcreaterole, rolcreatedb, rolcanlogin
FROM pg_roles
ORDER BY rolname;

-- List role memberships
SELECT 
    r.rolname AS role_name,
    m.rolname AS member_name
FROM pg_roles r
JOIN pg_auth_members am ON r.oid = am.roleid
JOIN pg_roles m ON am.member = m.oid
ORDER BY r.rolname, m.rolname;

-- List table privileges
SELECT 
    grantee,
    table_schema,
    table_name,
    privilege_type
FROM information_schema.table_privileges
WHERE grantee = 'user_name'
ORDER BY table_schema, table_name, privilege_type;

-- List database privileges
SELECT 
    datname,
    usename,
    has_database_privilege(usename, datname, 'CONNECT') AS can_connect,
    has_database_privilege(usename, datname, 'CREATE') AS can_create
FROM pg_database, pg_user
WHERE has_database_privilege(usename, datname, 'CONNECT')
ORDER BY datname, usename;

-- ============================================
-- MODIFY ROLE/USER
-- ============================================

-- Change password
ALTER USER user_name WITH PASSWORD 'NewPassword123!';

-- Change password expiration
ALTER USER user_name VALID UNTIL '2025-12-31';

-- Add privileges to role
ALTER ROLE user_name CREATEDB;
ALTER ROLE user_name CREATEROLE;
ALTER ROLE user_name SUPERUSER;

-- Remove privileges from role
ALTER ROLE user_name NOCREATEDB;
ALTER ROLE user_name NOCREATEROLE;
ALTER ROLE user_name NOSUPERUSER;

-- Set connection limit
ALTER ROLE user_name CONNECTION LIMIT 20;

-- Rename role
ALTER ROLE old_name RENAME TO new_name;

-- ============================================
-- REMOVE ROLE/USER
-- ============================================

-- Drop role (must revoke privileges first)
REVOKE ALL PRIVILEGES ON ALL TABLES IN SCHEMA schema_name FROM user_name;
DROP ROLE user_name;

-- Drop role with cascade (removes dependent objects)
DROP ROLE user_name CASCADE;

Bash script for user management:

#!/bin/bash

# PostgreSQL User Management Script
PGUSER="postgres"
PGHOST="localhost"
DB_NAME="database_name"
NEW_USER="db_user"
NEW_PASS="StrongPassword123!"

# Create user
psql -U "$PGUSER" -h "$PGHOST" << EOF
CREATE USER $NEW_USER WITH PASSWORD '$NEW_PASS';
GRANT CONNECT ON DATABASE $DB_NAME TO $NEW_USER;
GRANT USAGE ON SCHEMA public TO $NEW_USER;
GRANT SELECT, INSERT, UPDATE, DELETE ON ALL TABLES IN SCHEMA public TO $NEW_USER;
ALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT SELECT, INSERT, UPDATE, DELETE ON TABLES TO $NEW_USER;
EOF

# Verify user
psql -U "$PGUSER" -h "$PGHOST" -c "\du $NEW_USER"
DatabasePostgreSQLSecurityUser ManagementRoles

Create and manage SQL Server database backups with PowerShell and T-SQL

# SQL Server Database Backup Script
# Enterprise backup with validation and retention

param(
    [Parameter(Mandatory=$true)]
    [string]$ServerInstance,
    
    [Parameter(Mandatory=$true)]
    [string]$DatabaseName,
    
    [Parameter(Mandatory=$false)]
    [string]$BackupPath = "C:\Backups",
    
    [Parameter(Mandatory=$false)]
    [int]$RetentionDays = 30
)

Import-Module SqlServer -ErrorAction Stop

try {
    # Create backup directory if it doesn't exist
    if (-not (Test-Path $BackupPath)) {
        New-Item -ItemType Directory -Path $BackupPath -Force | Out-Null
    }
    
    $timestamp = Get-Date -Format "yyyyMMdd_HHmmss"
    $backupFile = Join-Path $BackupPath "$DatabaseName`_$timestamp.bak"
    
    Write-Host "Starting backup of database: $DatabaseName" -ForegroundColor Green
    
    # Perform full backup
    Backup-SqlDatabase `
        -ServerInstance $ServerInstance `
        -Database $DatabaseName `
        -BackupFile $backupFile `
        -BackupAction Database `
        -CompressionOption On `
        -Initialize
    
    Write-Host "Backup completed: $backupFile" -ForegroundColor Green
    
    # Verify backup
    $restoreResult = Restore-SqlDatabase `
        -ServerInstance $ServerInstance `
        -Database "${DatabaseName}_Verify" `
        -BackupFile $backupFile `
        -NoRecovery `
        -ErrorAction Stop
    
    # Clean up verification database
    Remove-SqlDatabase -ServerInstance $ServerInstance -Database "${DatabaseName}_Verify" -Force
    
    Write-Host "Backup verification successful" -ForegroundColor Green
    
    # Clean up old backups
    $cutoffDate = (Get-Date).AddDays(-$RetentionDays)
    Get-ChildItem -Path $BackupPath -Filter "$DatabaseName`_*.bak" | 
        Where-Object { $_.LastWriteTime -lt $cutoffDate } | 
        Remove-Item -Force
    
    Write-Host "Old backups cleaned up (retention: $RetentionDays days)" -ForegroundColor Yellow
    
} catch {
    Write-Error "Backup failed: $($_.Exception.Message)"
    exit 1
}

T-SQL backup commands:

-- Full database backup
BACKUP DATABASE [DatabaseName]
TO DISK = 'C:\Backups\DatabaseName.bak'
WITH COMPRESSION, INIT, CHECKSUM;

-- Differential backup
BACKUP DATABASE [DatabaseName]
TO DISK = 'C:\Backups\DatabaseName_diff.bak'
WITH DIFFERENTIAL, COMPRESSION, INIT, CHECKSUM;

-- Transaction log backup
BACKUP LOG [DatabaseName]
TO DISK = 'C:\Backups\DatabaseName.trn'
WITH COMPRESSION, INIT, CHECKSUM;

-- Backup to multiple files (striped)
BACKUP DATABASE [DatabaseName]
TO DISK = 'C:\Backups\File1.bak',
         DISK = 'D:\Backups\File2.bak'
WITH COMPRESSION, INIT, CHECKSUM;

-- Verify backup
RESTORE VERIFYONLY
FROM DISK = 'C:\Backups\DatabaseName.bak'
WITH CHECKSUM;
DatabaseSQL ServerBackupPowerShellT-SQL

Monitor SQL Server performance, identify bottlenecks, and optimize queries

-- SQL Server Performance Monitoring Queries
-- Enterprise performance analysis

-- ============================================
-- TOP QUERIES BY CPU
-- ============================================

SELECT TOP 20
    qs.execution_count,
    qs.total_worker_time / qs.execution_count AS avg_cpu_time,
    qs.total_worker_time AS total_cpu_time,
    qs.total_elapsed_time / qs.execution_count AS avg_elapsed_time,
    qs.total_logical_reads / qs.execution_count AS avg_logical_reads,
    SUBSTRING(qt.text, (qs.statement_start_offset/2) + 1,
        ((CASE qs.statement_end_offset
            WHEN -1 THEN DATALENGTH(qt.text)
            ELSE qs.statement_end_offset
        END - qs.statement_start_offset)/2) + 1) AS query_text,
    qt.text AS full_query_text,
    qp.query_plan
FROM sys.dm_exec_query_stats qs
CROSS APPLY sys.dm_exec_sql_text(qs.sql_handle) qt
CROSS APPLY sys.dm_exec_query_plan(qs.plan_handle) qp
ORDER BY qs.total_worker_time DESC;

-- ============================================
-- TOP QUERIES BY I/O
-- ============================================

SELECT TOP 20
    qs.execution_count,
    qs.total_logical_reads / qs.execution_count AS avg_logical_reads,
    qs.total_logical_reads AS total_logical_reads,
    qs.total_physical_reads / qs.execution_count AS avg_physical_reads,
    qs.total_physical_reads AS total_physical_reads,
    SUBSTRING(qt.text, (qs.statement_start_offset/2) + 1,
        ((CASE qs.statement_end_offset
            WHEN -1 THEN DATALENGTH(qt.text)
            ELSE qs.statement_end_offset
        END - qs.statement_start_offset)/2) + 1) AS query_text
FROM sys.dm_exec_query_stats qs
CROSS APPLY sys.dm_exec_sql_text(qs.sql_handle) qt
ORDER BY qs.total_logical_reads DESC;

-- ============================================
-- BLOCKING QUERIES
-- ============================================

SELECT 
    t1.session_id AS blocking_session_id,
    t1.wait_type,
    t1.wait_duration_ms,
    t1.blocking_session_id,
    t2.session_id AS blocked_session_id,
    DB_NAME(t1.database_id) AS database_name,
    t1.command,
    t1.text AS blocking_query,
    t2.text AS blocked_query
FROM sys.dm_exec_requests t1
LEFT JOIN sys.dm_exec_requests t2 ON t1.session_id = t2.blocking_session_id
CROSS APPLY sys.dm_exec_sql_text(t1.sql_handle) t1
CROSS APPLY sys.dm_exec_sql_text(t2.sql_handle) t2
WHERE t1.blocking_session_id > 0;

-- ============================================
-- MISSING INDEXES
-- ============================================

SELECT 
    migs.avg_total_user_cost * (migs.avg_user_impact / 100.0) * (migs.user_seeks + migs.user_scans) AS improvement_measure,
    'CREATE INDEX [missing_index_' + CONVERT(VARCHAR, mig.index_group_handle) + '_' + CONVERT(VARCHAR, mid.index_handle) + '_' + LEFT(PARSENAME(mid.statement, 1), 32) + ']' +
    ' ON ' + mid.statement +
    ' (' + ISNULL(mid.equality_columns, '') +
    CASE WHEN mid.equality_columns IS NOT NULL AND mid.inequality_columns IS NOT NULL THEN ',' ELSE '' END +
    ISNULL(mid.inequality_columns, '') + ')' +
    ISNULL(' INCLUDE (' + mid.included_columns + ')', '') AS create_index_statement,
    migs.*,
    mid.database_id,
    mid.[object_id]
FROM sys.dm_db_missing_index_groups mig
INNER JOIN sys.dm_db_missing_index_group_stats migs ON migs.group_handle = mig.index_group_handle
INNER JOIN sys.dm_db_missing_index_details mid ON mig.index_handle = mid.index_handle
WHERE migs.avg_total_user_cost * (migs.avg_user_impact / 100.0) * (migs.user_seeks + migs.user_scans) > 10
ORDER BY migs.avg_total_user_cost * migs.avg_user_impact * (migs.user_seeks + migs.user_scans) DESC;

-- ============================================
-- DATABASE FILE I/O STATISTICS
-- ============================================

SELECT 
    DB_NAME(database_id) AS database_name,
    file_id,
    io_stall_read_ms / num_of_reads AS avg_read_latency_ms,
    io_stall_write_ms / num_of_writes AS avg_write_latency_ms,
    io_stall / (num_of_reads + num_of_writes) AS avg_io_latency_ms,
    num_of_reads,
    num_of_writes,
    (num_of_bytes_read + num_of_bytes_written) / 1024 / 1024 AS total_mb
FROM sys.dm_io_virtual_file_stats(NULL, NULL)
ORDER BY avg_io_latency_ms DESC;

-- ============================================
-- WAIT STATISTICS
-- ============================================

SELECT TOP 20
    wait_type,
    waiting_tasks_count,
    wait_time_ms,
    max_wait_time_ms,
    signal_wait_time_ms,
    wait_time_ms - signal_wait_time_ms AS resource_wait_time_ms,
    CAST((wait_time_ms - signal_wait_time_ms) * 100.0 / SUM(wait_time_ms - signal_wait_time_ms) OVER() AS DECIMAL(5,2)) AS percent_resource_waits
FROM sys.dm_os_wait_stats
WHERE wait_type NOT IN (
    'CLR_SEMAPHORE', 'LAZYWRITER_SLEEP', 'RESOURCE_QUEUE', 'SLEEP_TASK',
    'SLEEP_SYSTEMTASK', 'SQLTRACE_BUFFER_FLUSH', 'WAITFOR', 'LOGMGR_QUEUE',
    'CHECKPOINT_QUEUE', 'REQUEST_FOR_DEADLOCK_SEARCH', 'XE_TIMER_EVENT',
    'BROKER_TO_FLUSH', 'BROKER_TASK_STOP', 'CLR_MANUAL_EVENT', 'CLR_AUTO_EVENT',
    'DISPATCHER_QUEUE_SEMAPHORE', 'FT_IFTS_SCHEDULER_IDLE_WAIT',
    'XE_DISPATCHER_WAIT', 'XE_DISPATCHER_JOIN', 'SQLTRACE_INCREMENTAL_FLUSH_SLEEP'
)
ORDER BY wait_time_ms DESC;

-- ============================================
-- ACTIVE CONNECTIONS
-- ============================================

SELECT 
    session_id,
    login_name,
    host_name,
    program_name,
    DB_NAME(database_id) AS database_name,
    status,
    cpu_time,
    memory_usage,
    total_scheduled_time,
    total_elapsed_time,
    last_request_start_time,
    last_request_end_time,
    reads,
    writes,
    logical_reads
FROM sys.dm_exec_sessions
WHERE is_user_process = 1
ORDER BY cpu_time DESC;

PowerShell monitoring:

# Get SQL Server performance counters
Get-Counter "\SQLServer:Databases(*)\Data File(s) Size (KB)" | 
    Select-Object -ExpandProperty CounterSamples | 
    Where-Object { $_.CookedValue -gt 0 } | 
    Sort-Object CookedValue -Descending | 
    Select-Object -First 10

# Monitor blocking
$query = @"
SELECT * FROM sys.dm_exec_requests 
WHERE blocking_session_id > 0
"@
Invoke-Sqlcmd -ServerInstance "ServerName" -Query $query
DatabaseSQL ServerPerformanceMonitoringOptimization

Create and manage SQL Server users, roles, and permissions

-- SQL Server User and Permission Management
-- Enterprise security best practices

-- ============================================
-- CREATE LOGIN (Server-level)
-- ============================================

-- Windows Authentication login
CREATE LOGIN [DOMAIN\username] FROM WINDOWS;

-- SQL Server Authentication login
CREATE LOGIN [sql_user] 
WITH PASSWORD = 'StrongPassword123!',
     CHECK_POLICY = ON,
     CHECK_EXPIRATION = ON,
     DEFAULT_DATABASE = [master];

-- ============================================
-- CREATE USER (Database-level)
-- ============================================

USE [DatabaseName];
GO

-- Create user from login
CREATE USER [db_user] FOR LOGIN [sql_user];

-- Create user with default schema
CREATE USER [db_user] 
FOR LOGIN [sql_user]
WITH DEFAULT_SCHEMA = [dbo];

-- ============================================
-- ROLE MANAGEMENT
-- ============================================

-- Add user to database role
ALTER ROLE [db_datareader] ADD MEMBER [db_user];
ALTER ROLE [db_datawriter] ADD MEMBER [db_user];
ALTER ROLE [db_ddladmin] ADD MEMBER [db_user];

-- Create custom database role
CREATE ROLE [CustomRole];
ALTER ROLE [CustomRole] ADD MEMBER [db_user];

-- Add user to server role
ALTER SERVER ROLE [sysadmin] ADD MEMBER [sql_user];
ALTER SERVER ROLE [dbcreator] ADD MEMBER [sql_user];

-- ============================================
-- GRANT PERMISSIONS
-- ============================================

-- Grant object-level permissions
GRANT SELECT, INSERT, UPDATE ON [dbo].[TableName] TO [db_user];
GRANT EXECUTE ON [dbo].[StoredProcedure] TO [db_user];

-- Grant schema-level permissions
GRANT SELECT, INSERT, UPDATE ON SCHEMA::[dbo] TO [db_user];

-- Grant database-level permissions
GRANT CREATE TABLE TO [db_user];
GRANT CREATE VIEW TO [db_user];
GRANT CREATE PROCEDURE TO [db_user];

-- Grant server-level permissions
GRANT VIEW SERVER STATE TO [sql_user];
GRANT VIEW ANY DATABASE TO [sql_user];

-- ============================================
-- DENY PERMISSIONS
-- ============================================

DENY DELETE ON [dbo].[TableName] TO [db_user];
DENY ALTER ON SCHEMA::[dbo] TO [db_user];

-- ============================================
-- VIEW PERMISSIONS
-- ============================================

-- List database users
SELECT name, type_desc, default_schema_name
FROM sys.database_principals
WHERE type IN ('S', 'U', 'G')
ORDER BY name;

-- List user permissions
SELECT 
    dp.name AS UserName,
    dp.type_desc AS UserType,
    p.permission_name,
    p.state_desc,
    o.name AS ObjectName
FROM sys.database_permissions p
JOIN sys.database_principals dp ON p.grantee_principal_id = dp.principal_id
LEFT JOIN sys.objects o ON p.major_id = o.object_id
WHERE dp.name = 'db_user';

-- List role members
SELECT 
    r.name AS RoleName,
    m.name AS MemberName
FROM sys.database_role_members rm
JOIN sys.database_principals r ON rm.role_principal_id = r.principal_id
JOIN sys.database_principals m ON rm.member_principal_id = m.principal_id
ORDER BY r.name, m.name;

-- ============================================
-- MODIFY USER
-- ============================================

-- Change user default schema
ALTER USER [db_user] WITH DEFAULT_SCHEMA = [sales];

-- Rename user
ALTER USER [old_name] WITH NAME = [new_name];

-- ============================================
-- REMOVE USER/LOGIN
-- ============================================

-- Remove user from role
ALTER ROLE [db_datareader] DROP MEMBER [db_user];

-- Drop database user
DROP USER [db_user];

-- Drop login
DROP LOGIN [sql_user];

PowerShell user management:

# Create SQL Server login
$login = New-SqlLogin -ServerInstance "ServerName" `
    -LoginName "sql_user" `
    -LoginType SqlLogin `
    -Password "StrongPassword123!" `
    -Enable `
    -EnforcePasswordPolicy `
    -EnforcePasswordExpiration

# Create database user
New-SqlUser -ServerInstance "ServerName" `
    -Database "DatabaseName" `
    -Name "db_user" `
    -LoginName "sql_user"

# Add user to role
Add-SqlRoleMember -ServerInstance "ServerName" `
    -Database "DatabaseName" `
    -RoleName "db_datareader" `
    -MemberName "db_user"
DatabaseSQL ServerSecurityUser ManagementPermissions

Manage firewalls on RHEL (firewalld) and Ubuntu/Debian (ufw)

#!/bin/bash

# Linux Firewall Management Script
# Supports firewalld (RHEL) and ufw (Ubuntu/Debian)

detect_firewall() {
    if command -v firewall-cmd &> /dev/null; then
        echo "firewalld"
    elif command -v ufw &> /dev/null; then
        echo "ufw"
    else
        echo "none"
    fi
}

FW_TYPE=$(detect_firewall)

if [ "$FW_TYPE" = "none" ]; then
    echo "No supported firewall detected"
    exit 1
fi

ACTION=$1

case $FW_TYPE in
    firewalld)
        case $ACTION in
            status)
                firewall-cmd --state
                firewall-cmd --list-all
                ;;
            start)
                systemctl start firewalld
                systemctl enable firewalld
                ;;
            stop)
                systemctl stop firewalld
                ;;
            reload)
                firewall-cmd --reload
                ;;
            add-port)
                local port=$2
                local protocol=${3:-tcp}
                firewall-cmd --permanent --add-port=$port/$protocol
                firewall-cmd --reload
                echo "Added port $port/$protocol"
                ;;
            remove-port)
                local port=$2
                local protocol=${3:-tcp}
                firewall-cmd --permanent --remove-port=$port/$protocol
                firewall-cmd --reload
                echo "Removed port $port/$protocol"
                ;;
            add-service)
                local service=$2
                firewall-cmd --permanent --add-service=$service
                firewall-cmd --reload
                echo "Added service $service"
                ;;
            list-ports)
                firewall-cmd --list-ports
                ;;
            list-services)
                firewall-cmd --list-services
                ;;
            *)
                echo "Usage: $0 <status|start|stop|reload|add-port|remove-port|add-service|list-ports|list-services>"
                ;;
        esac
        ;;
    ufw)
        case $ACTION in
            status)
                ufw status verbose
                ;;
            enable)
                ufw --force enable
                ;;
            disable)
                ufw disable
                ;;
            allow)
                local rule=$2
                ufw allow "$rule"
                echo "Added rule: $rule"
                ;;
            deny)
                local rule=$2
                ufw deny "$rule"
                echo "Added deny rule: $rule"
                ;;
            delete)
                local rule=$2
                ufw delete "$rule"
                echo "Deleted rule: $rule"
                ;;
            reset)
                ufw --force reset
                echo "Firewall reset"
                ;;
            *)
                echo "Usage: $0 <status|enable|disable|allow|deny|delete|reset>"
                ;;
        esac
        ;;
esac

Firewalld commands (RHEL/CentOS/Rocky):

# Check status
firewall-cmd --state
firewall-cmd --list-all

# Start/Stop/Enable
systemctl start firewalld
systemctl enable firewalld
systemctl stop firewalld

# Reload rules
firewall-cmd --reload

# Add port
firewall-cmd --permanent --add-port=80/tcp
firewall-cmd --reload

# Remove port
firewall-cmd --permanent --remove-port=80/tcp
firewall-cmd --reload

# Add service
firewall-cmd --permanent --add-service=http
firewall-cmd --reload

# List ports and services
firewall-cmd --list-ports
firewall-cmd --list-services

# Add rich rule
firewall-cmd --permanent --add-rich-rule='rule family="ipv4" source address="192.168.1.0/24" port port="22" protocol="tcp" accept'
firewall-cmd --reload

UFW commands (Ubuntu/Debian):

# Check status
ufw status
ufw status verbose
ufw status numbered

# Enable/Disable
ufw enable
ufw disable

# Allow port
ufw allow 80/tcp
ufw allow 22/tcp
ufw allow 443/udp

# Allow from specific IP
ufw allow from 192.168.1.100
ufw allow from 192.168.1.0/24 to any port 22

# Deny port
ufw deny 23/tcp

# Delete rule
ufw delete allow 80/tcp
ufw delete 1  # Delete by number

# Reset firewall
ufw reset

# Show app profiles
ufw app list
ufw allow 'Apache Full'
LinuxFirewallSecurityNetworkingfirewalldufw

Configure network interfaces on RHEL, Ubuntu, and Debian

#!/bin/bash

# Linux Network Configuration Script
# Works with NetworkManager (RHEL 7+, Ubuntu 18.04+) and traditional configs

detect_network_manager() {
    if command -v nmcli &> /dev/null; then
        echo "NetworkManager"
    elif [ -f /etc/network/interfaces ]; then
        echo "networking"
    else
        echo "unknown"
    fi
}

NET_MGR=$(detect_network_manager)
ACTION=$1

case $NET_MGR in
    NetworkManager)
        case $ACTION in
            list)
                nmcli device status
                nmcli connection show
                ;;
            up)
                local conn=$2
                nmcli connection up "$conn"
                ;;
            down)
                local conn=$2
                nmcli connection down "$conn"
                ;;
            add-static)
                local iface=$2
                local ip=$3
                local gateway=$4
                local dns=${5:-8.8.8.8}
                
                nmcli connection add type ethernet con-name "$iface-static" ifname "$iface" ipv4.addresses "$ip" ipv4.gateway "$gateway" ipv4.dns "$dns" ipv4.method manual
                nmcli connection up "$iface-static"
                ;;
            modify-dns)
                local conn=$2
                local dns=$3
                nmcli connection modify "$conn" ipv4.dns "$dns"
                nmcli connection up "$conn"
                ;;
            *)
                echo "Usage: $0 <list|up|down|add-static|modify-dns> [options]"
                ;;
        esac
        ;;
    networking)
        echo "Using traditional /etc/network/interfaces configuration"
        echo "Edit /etc/network/interfaces and restart networking:"
        echo "  systemctl restart networking  # Debian"
        echo "  systemctl restart NetworkManager  # Ubuntu"
        ;;
esac

NetworkManager (RHEL 7+, Ubuntu 18.04+):

# List devices and connections
nmcli device status
nmcli connection show

# Show connection details
nmcli connection show "connection-name"

# Bring connection up/down
nmcli connection up "connection-name"
nmcli connection down "connection-name"

# Add static IP connection
nmcli connection add type ethernet con-name "eth0-static" ifname eth0 \
    ipv4.addresses 192.168.1.100/24 \
    ipv4.gateway 192.168.1.1 \
    ipv4.dns "8.8.8.8 8.8.4.4" \
    ipv4.method manual

# Modify existing connection
nmcli connection modify "connection-name" ipv4.addresses 192.168.1.101/24
nmcli connection up "connection-name"

# Set DNS
nmcli connection modify "connection-name" ipv4.dns "8.8.8.8"
nmcli connection up "connection-name"

# Enable/Disable connection
nmcli connection up "connection-name"
nmcli connection down "connection-name"

# Delete connection
nmcli connection delete "connection-name"

Traditional configuration (Debian/older Ubuntu):

# Edit /etc/network/interfaces
# Static IP example:
# auto eth0
# iface eth0 inet static
#     address 192.168.1.100
#     netmask 255.255.255.0
#     gateway 192.168.1.1
#     dns-nameservers 8.8.8.8 8.8.4.4

# Restart networking
systemctl restart networking  # Debian
systemctl restart NetworkManager  # Ubuntu

# Or use ifup/ifdown
ifup eth0
ifdown eth0

Common network commands (all distributions):

# Show IP addresses
ip addr show
ifconfig

# Show routing table
ip route show
route -n

# Test connectivity
ping -c 4 8.8.8.8
ping -c 4 google.com

# Show network statistics
ss -tuln
netstat -tuln

# Restart network
systemctl restart NetworkManager  # RHEL/Ubuntu
systemctl restart networking      # Debian
LinuxNetworkingNetwork ConfigurationSystem Administration

Create, modify, and manage Linux users and groups across distributions

#!/bin/bash

# Linux User Management Script
# Works across RHEL, Ubuntu, and Debian

ACTION=$1
USERNAME=$2

if [ -z "$ACTION" ] || [ -z "$USERNAME" ]; then
    echo "Usage: $0 <create|delete|modify|lock|unlock|list> <username> [options]"
    exit 1
fi

create_user() {
    local username=$1
    local shell=${2:-/bin/bash}
    local home_dir=${3:-/home/$username}
    local groups=${4:-}
    
    echo "Creating user: $username"
    useradd -m -s "$shell" -d "$home_dir" "$username"
    
    if [ -n "$groups" ]; then
        usermod -aG "$groups" "$username"
    fi
    
    # Set initial password (user should change on first login)
    passwd "$username"
    
    echo "User $username created successfully"
    id "$username"
}

delete_user() {
    local username=$1
    local remove_home=${2:-false}
    
    echo "Deleting user: $username"
    
    if [ "$remove_home" = "true" ]; then
        userdel -r "$username"
        echo "User $username and home directory deleted"
    else
        userdel "$username"
        echo "User $username deleted (home directory preserved)"
    fi
}

modify_user() {
    local username=$1
    local option=$2
    local value=$3
    
    case $option in
        shell)
            usermod -s "$value" "$username"
            echo "Changed shell for $username to $value"
            ;;
        home)
            usermod -d "$value" -m "$username"
            echo "Changed home directory for $username to $value"
            ;;
        groups)
            usermod -aG "$value" "$username"
            echo "Added $username to groups: $value"
            ;;
        *)
            echo "Invalid option: $option"
            exit 1
            ;;
    esac
}

lock_user() {
    local username=$1
    usermod -L "$username"
    echo "Account $username locked"
}

unlock_user() {
    local username=$1
    usermod -U "$username"
    echo "Account $username unlocked"
}

list_users() {
    echo "System users:"
    awk -F: '$3 < 1000 {print $1, $3}' /etc/passwd
    echo ""
    echo "Regular users:"
    awk -F: '$3 >= 1000 {print $1, $3}' /etc/passwd
}

case $ACTION in
    create)
        create_user "$USERNAME" "$3" "$4" "$5"
        ;;
    delete)
        delete_user "$USERNAME" "$3"
        ;;
    modify)
        modify_user "$USERNAME" "$3" "$4"
        ;;
    lock)
        lock_user "$USERNAME"
        ;;
    unlock)
        unlock_user "$USERNAME"
        ;;
    list)
        list_users
        ;;
    *)
        echo "Invalid action: $ACTION"
        exit 1
        ;;
esac

Common user management commands:

# Create user
useradd -m -s /bin/bash username
useradd -m -s /bin/bash -G sudo,www-data username  # With groups

# Delete user
userdel username
userdel -r username  # Remove home directory too

# Modify user
usermod -s /bin/zsh username  # Change shell
usermod -d /new/home username  # Change home directory
usermod -aG group1,group2 username  # Add to groups
usermod -L username  # Lock account
usermod -U username  # Unlock account

# Set password
passwd username
chage -M 90 username  # Set password max age

# Create group
groupadd groupname

# Add user to group
usermod -aG groupname username
gpasswd -a username groupname

# Remove user from group
gpasswd -d username groupname

# List users
cat /etc/passwd
getent passwd

# List groups
cat /etc/group
getent group

# Show user info
id username
groups username
finger username  # If installed

# Switch user
su - username
sudo -u username command
LinuxUser ManagementSystem AdministrationSecurity

Configure and secure SSH on Linux systems

#!/bin/bash

# SSH Configuration and Hardening Script
# Applies security best practices to SSH configuration

SSH_CONFIG="/etc/ssh/sshd_config"
BACKUP_FILE="/etc/ssh/sshd_config.backup.$(date +%Y%m%d_%H%M%S)"

# Backup original config
cp "$SSH_CONFIG" "$BACKUP_FILE"
echo "Backup created: $BACKUP_FILE"

# Function to set SSH config option
set_ssh_option() {
    local option=$1
    local value=$2
    
    # Remove existing option if present
    sed -i "/^$option/d" "$SSH_CONFIG"
    
    # Add new option
    echo "$option $value" >> "$SSH_CONFIG"
    echo "Set: $option $value"
}

# Apply security hardening
echo "Applying SSH security hardening..."

# Disable root login
set_ssh_option "PermitRootLogin" "no"

# Disable password authentication (use keys only)
set_ssh_option "PasswordAuthentication" "no"
set_ssh_option "PubkeyAuthentication" "yes"

# Disable empty passwords
set_ssh_option "PermitEmptyPasswords" "no"

# Set protocol version (SSH 2 only)
set_ssh_option "Protocol" "2"

# Set maximum authentication attempts
set_ssh_option "MaxAuthTries" "3"

# Set login grace time
set_ssh_option "LoginGraceTime" "60"

# Disable X11 forwarding (if not needed)
set_ssh_option "X11Forwarding" "no"

# Set allowed users (uncomment and modify as needed)
# set_ssh_option "AllowUsers" "user1 user2"

# Set idle timeout
set_ssh_option "ClientAliveInterval" "300"
set_ssh_option "ClientAliveCountMax" "2"

# Disable unused authentication methods
set_ssh_option "ChallengeResponseAuthentication" "no"
set_ssh_option "UsePAM" "yes"

# Set banner (create /etc/ssh/banner first)
# set_ssh_option "Banner" "/etc/ssh/banner"

# Restart SSH service
echo ""
read -p "Restart SSH service? (yes/no): " restart
if [ "$restart" = "yes" ]; then
    # Test config first
    sshd -t
    if [ $? -eq 0 ]; then
        systemctl restart sshd  # RHEL
        # systemctl restart ssh   # Ubuntu/Debian
        echo "SSH service restarted"
    else
        echo "ERROR: SSH config test failed. Restore backup if needed."
        exit 1
    fi
else
    echo "SSH config updated. Restart manually: systemctl restart sshd"
fi

SSH configuration file (/etc/ssh/sshd_config):

# Security hardening options
PermitRootLogin no
PasswordAuthentication no
PubkeyAuthentication yes
PermitEmptyPasswords no
Protocol 2
MaxAuthTries 3
LoginGraceTime 60
X11Forwarding no
ClientAliveInterval 300
ClientAliveCountMax 2
ChallengeResponseAuthentication no

# Allow specific users
AllowUsers user1 user2

# Allow specific groups
AllowGroups sshusers

# Deny specific users
DenyUsers baduser
DenyGroups badgroup

# Change default port (uncomment and modify)
# Port 2222

# Banner
Banner /etc/ssh/banner

SSH key management:

# Generate SSH key pair
ssh-keygen -t ed25519 -C "[email protected]"
ssh-keygen -t rsa -b 4096 -C "[email protected]"

# Copy public key to remote server
ssh-copy-id user@remote-host
# Or manually:
cat ~/.ssh/id_rsa.pub | ssh user@remote-host "mkdir -p ~/.ssh && cat >> ~/.ssh/authorized_keys"

# Set correct permissions
chmod 700 ~/.ssh
chmod 600 ~/.ssh/authorized_keys
chmod 600 ~/.ssh/id_rsa
chmod 644 ~/.ssh/id_rsa.pub

# Test SSH connection
ssh -v user@remote-host

# SSH with specific key
ssh -i ~/.ssh/specific_key user@remote-host

# Disable password authentication for specific user
# Edit ~/.ssh/authorized_keys and add:
# command="command_to_run" ssh-rsa ...

SSH service management:

# Check SSH status
systemctl status sshd  # RHEL
systemctl status ssh    # Ubuntu/Debian

# Restart SSH
systemctl restart sshd
systemctl restart ssh

# Test SSH config before restarting
sshd -t

# View SSH logs
journalctl -u sshd -f
tail -f /var/log/auth.log  # Ubuntu/Debian
tail -f /var/log/secure    # RHEL
LinuxSSHSecurityRemote Access

Essential apt and dpkg commands for Debian package management

#!/bin/bash

# Debian Package Management Script
# Uses apt and dpkg commands

# Update package lists
update_package_lists() {
    echo "Updating package lists..."
    apt update
}

# Upgrade all packages
upgrade_all() {
    echo "Upgrading all packages..."
    apt upgrade -y
}

# Full system upgrade
full_upgrade() {
    echo "Performing full system upgrade..."
    apt full-upgrade -y
}

# Install package from .deb file
install_deb_file() {
    local deb_file=$1
    if [ ! -f "$deb_file" ]; then
        echo "Error: File not found: $deb_file"
        exit 1
    fi
    echo "Installing $deb_file..."
    dpkg -i "$deb_file"
    # Fix dependencies if needed
    apt-get install -f -y
}

# Install package(s)
install_package() {
    local packages="$@"
    echo "Installing: $packages"
    apt install -y $packages
}

# Remove package
remove_package() {
    local package=$1
    echo "Removing: $package"
    apt remove -y "$package"
}

# Purge package (remove with config)
purge_package() {
    local package=$1
    echo "Purging: $package"
    apt purge -y "$package"
}

# Search packages
search_packages() {
    local search_term=$1
    apt search "$search_term"
}

# Show package information
show_package_info() {
    local package=$1
    apt show "$package"
}

# List installed packages
list_installed() {
    dpkg -l
}

# Check if package is installed
is_installed() {
    local package=$1
    dpkg -l | grep -q "^ii.*$package" && echo "Installed" || echo "Not installed"
}

# Show package files
show_package_files() {
    local package=$1
    dpkg -L "$package"
}

# Find which package owns a file
find_package_by_file() {
    local file=$1
    dpkg -S "$file"
}

# Reconfigure package
reconfigure_package() {
    local package=$1
    dpkg-reconfigure "$package"
}

# Hold package (prevent updates)
hold_package() {
    local package=$1
    apt-mark hold "$package"
}

# Unhold package
unhold_package() {
    local package=$1
    apt-mark unhold "$package"
}

# List held packages
list_held() {
    apt-mark showhold
}

Common commands:

# Update and upgrade
apt update
apt upgrade
apt full-upgrade

# Install package
apt install package_name
apt-get install package_name

# Install .deb file
dpkg -i package.deb
apt-get install -f  # Fix dependencies

# Remove package
apt remove package_name
apt-get remove package_name

# Purge package
apt purge package_name
apt-get purge package_name

# Search packages
apt search keyword
apt-cache search keyword

# Show package info
apt show package_name
dpkg -s package_name

# List installed packages
dpkg -l
dpkg -l | grep package_name

# Show files in package
dpkg -L package_name

# Find package by file
dpkg -S /path/to/file

# Reconfigure package
dpkg-reconfigure package_name

# Hold/Unhold package
apt-mark hold package_name
apt-mark unhold package_name
apt-mark showhold
LinuxDebianPackage Managementaptdpkg

Essential yum and dnf commands for RHEL/CentOS/Rocky Linux package management

#!/bin/bash

# RHEL Package Management Guide
# Works with RHEL 7 (yum) and RHEL 8+ (dnf)

# Determine package manager
if command -v dnf &> /dev/null; then
    PKG_MGR="dnf"
elif command -v yum &> /dev/null; then
    PKG_MGR="yum"
else
    echo "Error: Neither dnf nor yum found"
    exit 1
fi

echo "Using package manager: $PKG_MGR"

# Update package cache
echo "Updating package cache..."
$PKG_MGR makecache

# Update all packages
echo "Updating all packages..."
$PKG_MGR update -y

# Install a package
install_package() {
    local package=$1
    echo "Installing $package..."
    $PKG_MGR install -y "$package"
}

# Remove a package
remove_package() {
    local package=$1
    echo "Removing $package..."
    $PKG_MGR remove -y "$package"
}

# Search for packages
search_packages() {
    local search_term=$1
    echo "Searching for: $search_term"
    $PKG_MGR search "$search_term"
}

# List installed packages
list_installed() {
    $PKG_MGR list installed
}

# Show package information
show_package_info() {
    local package=$1
    $PKG_MGR info "$package"
}

# Check for updates
check_updates() {
    $PKG_MGR check-update
}

# Clean package cache
clean_cache() {
    $PKG_MGR clean all
}

# Install from specific repository
install_from_repo() {
    local repo=$1
    local package=$2
    $PKG_MGR install -y --enablerepo="$repo" "$package"
}

# List available repositories
list_repos() {
    $PKG_MGR repolist all
}

# Enable repository
enable_repo() {
    local repo=$1
    $PKG_MGR config-manager --enable "$repo"
}

# Disable repository
disable_repo() {
    local repo=$1
    $PKG_MGR config-manager --disable "$repo"
}

Common commands:

# RHEL 8+ (dnf)
dnf install package_name
dnf update
dnf search keyword
dnf remove package_name
dnf list installed
dnf info package_name
dnf clean all

# RHEL 7 (yum)
yum install package_name
yum update
yum search keyword
yum remove package_name
yum list installed
yum info package_name
yum clean all

# Install EPEL repository (RHEL 7)
yum install epel-release

# Install EPEL repository (RHEL 8+)
dnf install epel-release

# Group install (useful for development tools)
dnf groupinstall "Development Tools"
yum groupinstall "Development Tools"
LinuxRHELPackage Managementyumdnf

Manage systemd services on RHEL/CentOS/Rocky Linux

#!/bin/bash

# RHEL Service Management Script
# Works with systemd (RHEL 7+)

SERVICE_NAME=$1
ACTION=$2

if [ -z "$SERVICE_NAME" ] || [ -z "$ACTION" ]; then
    echo "Usage: $0 <service_name> <start|stop|restart|reload|status|enable|disable>"
    exit 1
fi

case $ACTION in
    start)
        systemctl start "$SERVICE_NAME"
        systemctl status "$SERVICE_NAME" --no-pager
        ;;
    stop)
        systemctl stop "$SERVICE_NAME"
        systemctl status "$SERVICE_NAME" --no-pager
        ;;
    restart)
        systemctl restart "$SERVICE_NAME"
        systemctl status "$SERVICE_NAME" --no-pager
        ;;
    reload)
        systemctl reload "$SERVICE_NAME"
        systemctl status "$SERVICE_NAME" --no-pager
        ;;
    status)
        systemctl status "$SERVICE_NAME"
        ;;
    enable)
        systemctl enable "$SERVICE_NAME"
        echo "Service $SERVICE_NAME enabled to start on boot"
        ;;
    disable)
        systemctl disable "$SERVICE_NAME"
        echo "Service $SERVICE_NAME disabled from starting on boot"
        ;;
    *)
        echo "Invalid action: $ACTION"
        exit 1
        ;;
esac

# Check if service is active
if systemctl is-active --quiet "$SERVICE_NAME"; then
    echo "Service $SERVICE_NAME is running"
else
    echo "Service $SERVICE_NAME is not running"
fi

Common service commands:

# Start/Stop/Restart services
systemctl start httpd
systemctl stop httpd
systemctl restart httpd
systemctl reload httpd  # Reload config without downtime

# Enable/Disable services (start on boot)
systemctl enable httpd
systemctl disable httpd

# Check service status
systemctl status httpd
systemctl is-active httpd
systemctl is-enabled httpd

# List all services
systemctl list-units --type=service
systemctl list-units --type=service --state=running

# View service logs
journalctl -u httpd
journalctl -u httpd -f  # Follow logs
journalctl -u httpd --since "1 hour ago"

# Mask/Unmask services (prevent starting)
systemctl mask httpd
systemctl unmask httpd

# Reload systemd configuration
systemctl daemon-reload
LinuxRHELsystemdService Management

Essential apt and apt-get commands for Ubuntu/Debian package management

#!/bin/bash

# Ubuntu Package Management Script
# Uses apt (Ubuntu 16.04+) or apt-get (older versions)

# Update package lists
update_package_lists() {
    echo "Updating package lists..."
    apt update
}

# Upgrade all packages
upgrade_all() {
    echo "Upgrading all packages..."
    apt upgrade -y
}

# Full system upgrade (dist-upgrade)
full_upgrade() {
    echo "Performing full system upgrade..."
    apt full-upgrade -y
}

# Install package(s)
install_package() {
    local packages="$@"
    echo "Installing: $packages"
    apt install -y $packages
}

# Remove package
remove_package() {
    local package=$1
    echo "Removing: $package"
    apt remove -y "$package"
}

# Remove package and configuration files
purge_package() {
    local package=$1
    echo "Purging: $package (including config files)"
    apt purge -y "$package"
}

# Search for packages
search_packages() {
    local search_term=$1
    echo "Searching for: $search_term"
    apt search "$search_term"
}

# Show package information
show_package_info() {
    local package=$1
    apt show "$package"
}

# List installed packages
list_installed() {
    apt list --installed
}

# List upgradable packages
list_upgradable() {
    apt list --upgradable
}

# Clean package cache
clean_cache() {
    apt clean
    apt autoclean
}

# Remove unused packages
autoremove() {
    apt autoremove -y
}

# Fix broken dependencies
fix_broken() {
    apt --fix-broken install
}

# Add PPA (Personal Package Archive)
add_ppa() {
    local ppa=$1
    add-apt-repository -y "ppa:$ppa"
    apt update
}

# Remove PPA
remove_ppa() {
    local ppa=$1
    add-apt-repository --remove -y "ppa:$ppa"
    apt update
}

Common commands:

# Update package lists
apt update
apt-get update

# Upgrade packages
apt upgrade
apt-get upgrade

# Full system upgrade
apt full-upgrade
apt-get dist-upgrade

# Install package
apt install package_name
apt-get install package_name

# Remove package
apt remove package_name
apt-get remove package_name

# Purge package (remove with config)
apt purge package_name
apt-get purge package_name

# Search packages
apt search keyword
apt-cache search keyword

# Show package info
apt show package_name
apt-cache show package_name

# List installed packages
apt list --installed
dpkg -l

# Clean cache
apt clean
apt autoclean

# Remove unused packages
apt autoremove

# Fix broken dependencies
apt --fix-broken install

# Add PPA
add-apt-repository ppa:user/repo
apt update
LinuxUbuntuPackage Managementaptapt-get

Manage snap packages on Ubuntu systems

#!/bin/bash

# Ubuntu Snap Package Management Script

ACTION=$1
PACKAGE_NAME=$2

if [ -z "$ACTION" ]; then
    echo "Usage: $0 <install|remove|update|list|info|search> [package_name]"
    exit 1
fi

case $ACTION in
    install)
        if [ -z "$PACKAGE_NAME" ]; then
            echo "Error: Package name required for install"
            exit 1
        fi
        echo "Installing $PACKAGE_NAME..."
        snap install "$PACKAGE_NAME"
        ;;
    remove)
        if [ -z "$PACKAGE_NAME" ]; then
            echo "Error: Package name required for remove"
            exit 1
        fi
        echo "Removing $PACKAGE_NAME..."
        snap remove "$PACKAGE_NAME"
        ;;
    update)
        if [ -z "$PACKAGE_NAME" ]; then
            echo "Updating all snap packages..."
            snap refresh
        else
            echo "Updating $PACKAGE_NAME..."
            snap refresh "$PACKAGE_NAME"
        fi
        ;;
    list)
        echo "Installed snap packages:"
        snap list
        ;;
    info)
        if [ -z "$PACKAGE_NAME" ]; then
            echo "Error: Package name required for info"
            exit 1
        fi
        snap info "$PACKAGE_NAME"
        ;;
    search)
        if [ -z "$PACKAGE_NAME" ]; then
            echo "Error: Search term required"
            exit 1
        fi
        snap find "$PACKAGE_NAME"
        ;;
    *)
        echo "Invalid action: $ACTION"
        exit 1
        ;;
esac

Common snap commands:

# Install snap package
snap install package_name
snap install package_name --channel=edge  # Install from edge channel

# Remove snap package
snap remove package_name

# Update all snaps
snap refresh

# Update specific snap
snap refresh package_name

# List installed snaps
snap list

# Show snap information
snap info package_name

# Search for snaps
snap find keyword

# Enable/Disable snap
snap enable package_name
snap disable package_name

# View snap changes
snap changes

# Revert snap to previous version
snap revert package_name

# Set snap channel
snap switch --channel=stable package_name
LinuxUbuntuSnapPackage Management

Add users to Active Directory groups with validation and error handling for enterprise environments

# Enterprise group membership addition with validation
param(
    [Parameter(Mandatory=$true)]
    [string]$GroupName,
    
    [Parameter(Mandatory=$true)]
    [string[]]$UserNames
)

try {
    # Verify group exists
    $Group = Get-ADGroup -Identity $GroupName -ErrorAction Stop
    
    # Verify all users exist before adding
    $ValidUsers = @()
    foreach ($UserName in $UserNames) {
        $User = Get-ADUser -Identity $UserName -ErrorAction SilentlyContinue
        if ($User) {
            $ValidUsers += $User
        } else {
            Write-Warning "User $UserName not found, skipping"
        }
    }
    
    if ($ValidUsers.Count -eq 0) {
        Write-Error "No valid users to add"
        exit 1
    }
    
    # Add users to group
    Add-ADGroupMember -Identity $GroupName -Members $ValidUsers -ErrorAction Stop
    
    Write-Host "Added $($ValidUsers.Count) user(s) to $GroupName" -ForegroundColor Green
} catch {
    Write-Error "Failed to add users to group: $($_.Exception.Message)"
    exit 1
}

Quick version:

Add-ADGroupMember -Identity "Domain Admins" -Members "jdoe"

Add multiple users:

Add-ADGroupMember -Identity "Sales Team" -Members "user1", "user2", "user3"
PowerShellActive DirectoryGroup ManagementSecurity

Security audit of all privileged accounts in Active Directory

# Audit all administrative accounts
$AdminGroups = @("Domain Admins", "Enterprise Admins", "Schema Admins", "Administrators")

$AdminAccounts = @()
foreach ($Group in $AdminGroups) {
    try {
        $Members = Get-ADGroupMember -Identity $Group -Recursive | 
            Where-Object {$_.objectClass -eq 'user'} | 
            Get-ADUser -Properties Name, EmailAddress, Enabled, LastLogonDate, PasswordLastSet, PasswordNeverExpires
        
        foreach ($Member in $Members) {
            $AdminAccounts += [PSCustomObject]@{
                Name = $Member.Name
                SamAccountName = $Member.SamAccountName
                EmailAddress = $Member.EmailAddress
                AdminGroup = $Group
                Enabled = $Member.Enabled
                LastLogonDate = $Member.LastLogonDate
                PasswordLastSet = $Member.PasswordLastSet
                PasswordNeverExpires = $Member.PasswordNeverExpires
            }
        }
    } catch {
        Write-Warning "Could not process group $Group : $($_.Exception.Message)"
    }
}

$AdminAccounts | Sort-Object Name | Format-Table -AutoSize

# Export to CSV
$AdminAccounts | Export-Csv -Path "C:\Reports\AdminAccounts_$(Get-Date -Format 'yyyyMMdd').csv" -NoTypeInformation -Encoding UTF8
PowerShellActive DirectorySecurityAuditCompliance

Perform operations on multiple users from CSV import for enterprise provisioning

# Bulk user creation from CSV
# CSV columns: FirstName, LastName, Department, OUPath, InitialPassword
$Users = Import-Csv -Path "C:\Data\NewUsers.csv"

foreach ($User in $Users) {
    $DisplayName = "$($User.FirstName) $($User.LastName)"
    $SamAccountName = ($User.FirstName[0] + $User.LastName).ToLower()
    $SecurePassword = ConvertTo-SecureString $User.InitialPassword -AsPlainText -Force
    
    try {
        New-ADUser -Name $DisplayName `
            -GivenName $User.FirstName `
            -Surname $User.LastName `
            -SamAccountName $SamAccountName `
            -UserPrincipalName "$SamAccountName@$env:USERDNSDOMAIN" `
            -AccountPassword $SecurePassword `
            -Enabled $true `
            -ChangePasswordAtLogon $true `
            -Path $User.OUPath `
            -Department $User.Department `
            -ErrorAction Stop
        
        Write-Host "Created: $DisplayName" -ForegroundColor Green
    } catch {
        Write-Warning "Failed to create $DisplayName : $($_.Exception.Message)"
    }
}

Bulk disable users from CSV:

$Users = Import-Csv -Path "C:\Data\UsersToDisable.csv"
foreach ($User in $Users) {
    Disable-ADAccount -Identity $User.SamAccountName
    Write-Host "Disabled: $($User.SamAccountName)"
}
PowerShellActive DirectoryBulk OperationsProvisioning

Find users with passwords expiring soon for proactive password management

# Find users with passwords expiring in the next 14 days
$DaysUntilExpiration = 14
$ExpirationDate = (Get-Date).AddDays($DaysUntilExpiration)

Get-ADUser -Filter {Enabled -eq $true -and PasswordNeverExpires -eq $false} -Properties PasswordLastSet, PasswordExpired, msDS-UserPasswordExpiryTimeComputed | 
    Where-Object {
        $ExpiryDate = [DateTime]::FromFileTime($_.'msDS-UserPasswordExpiryTimeComputed')
        $ExpiryDate -le $ExpirationDate -and $ExpiryDate -gt (Get-Date)
    } | 
    Select-Object Name, SamAccountName, EmailAddress, 
        @{Name='PasswordExpires';Expression={[DateTime]::FromFileTime($_.'msDS-UserPasswordExpiryTimeComputed')}} | 
    Sort-Object PasswordExpires

Export to CSV for notification:

$DaysUntilExpiration = 14
$ExpirationDate = (Get-Date).AddDays($DaysUntilExpiration)

Get-ADUser -Filter {Enabled -eq $true -and PasswordNeverExpires -eq $false} -Properties EmailAddress, msDS-UserPasswordExpiryTimeComputed | 
    Where-Object {
        $ExpiryDate = [DateTime]::FromFileTime($_.'msDS-UserPasswordExpiryTimeComputed')
        $ExpiryDate -le $ExpirationDate -and $ExpiryDate -gt (Get-Date)
    } | 
    Select-Object Name, SamAccountName, EmailAddress, 
        @{Name='PasswordExpires';Expression={[DateTime]::FromFileTime($_.'msDS-UserPasswordExpiryTimeComputed')}} | 
    Export-Csv -Path "C:\Reports\PasswordExpiring.csv" -NoTypeInformation -Encoding UTF8
PowerShellActive DirectoryPassword ManagementSecurity

Create a new Active Directory user with enterprise best practices, validation, and proper OU placement

# Enterprise user creation with validation and error handling
param(
    [Parameter(Mandatory=$true)]
    [string]$FirstName,
    
    [Parameter(Mandatory=$true)]
    [string]$LastName,
    
    [Parameter(Mandatory=$true)]
    [string]$Department,
    
    [Parameter(Mandatory=$true)]
    [string]$OUPath,
    
    [Parameter(Mandatory=$true)]
    [SecureString]$InitialPassword
)

$DisplayName = "$FirstName $LastName"
$SamAccountName = ($FirstName[0] + $LastName).ToLower()
$UPN = "$SamAccountName@$env:USERDNSDOMAIN"

# Check if user already exists
if (Get-ADUser -Filter {SamAccountName -eq $SamAccountName} -ErrorAction SilentlyContinue) {
    Write-Error "User $SamAccountName already exists"
    exit 1
}

# Verify OU exists
if (-not (Get-ADOrganizationalUnit -Identity $OUPath -ErrorAction SilentlyContinue)) {
    Write-Error "OU path $OUPath does not exist"
    exit 1
}

try {
    New-ADUser -Name $DisplayName `
        -GivenName $FirstName `
        -Surname $LastName `
        -SamAccountName $SamAccountName `
        -UserPrincipalName $UPN `
        -AccountPassword $InitialPassword `
        -Enabled $true `
        -ChangePasswordAtLogon $true `
        -Path $OUPath `
        -Department $Department `
        -DisplayName $DisplayName `
        -ErrorAction Stop
    
    Write-Host "User $DisplayName created successfully" -ForegroundColor Green
} catch {
    Write-Error "Failed to create user: $($_.Exception.Message)"
    exit 1
}

Quick version for testing:

$SecurePassword = ConvertTo-SecureString "TempPassword123!" -AsPlainText -Force
New-ADUser -Name "John Doe" `
    -SamAccountName "jdoe" `
    -UserPrincipalName "[email protected]" `
    -AccountPassword $SecurePassword `
    -Enabled $true `
    -ChangePasswordAtLogon $true `
    -Path "OU=Users,DC=domain,DC=com" `
    -Department "IT" `
    -Title "Systems Administrator"
PowerShellActive DirectoryUser ManagementProvisioning

Export Active Directory users with comprehensive properties for enterprise reporting and audits

# Comprehensive user export for enterprise reporting
$ExportPath = "C:\Reports\ADUsers_$(Get-Date -Format 'yyyyMMdd').csv"

Get-ADUser -Filter * -Properties Name, SamAccountName, EmailAddress, Department, Title, Enabled, 
    LastLogonDate, WhenCreated, WhenChanged, PasswordLastSet, PasswordNeverExpires, 
    LockedOut, DistinguishedName, Manager | 
    Select-Object Name, SamAccountName, EmailAddress, Department, Title, Enabled, 
        LastLogonDate, WhenCreated, WhenChanged, PasswordLastSet, PasswordNeverExpires, 
        LockedOut, DistinguishedName, 
        @{Name='Manager';Expression={(Get-ADUser $_.Manager -ErrorAction SilentlyContinue).Name}} | 
    Export-Csv -Path $ExportPath -NoTypeInformation -Encoding UTF8

Write-Host "Export completed: $ExportPath" -ForegroundColor Green

Export users from specific OU:

Get-ADUser -Filter * -SearchBase "OU=Users,DC=domain,DC=com" -Properties Name, EmailAddress, Department, Title, Enabled, LastLogonDate | 
    Select-Object Name, SamAccountName, EmailAddress, Department, Title, Enabled, LastLogonDate | 
    Export-Csv -Path "C:\Reports\Users_OU.csv" -NoTypeInformation -Encoding UTF8

Export only enabled users:

Get-ADUser -Filter {Enabled -eq $true} -Properties Name, EmailAddress, Department, Title, LastLogonDate | 
    Select-Object Name, SamAccountName, EmailAddress, Department, Title, LastLogonDate | 
    Export-Csv -Path "C:\Reports\EnabledUsers.csv" -NoTypeInformation -Encoding UTF8
PowerShellActive DirectoryExportReportingAudit

Get all users who are members of a specific group, including nested groups

# Get all direct and nested members of a group
function Get-ADGroupMembersRecursive {
    param([string]$GroupName)
    
    $Members = @()
    $Group = Get-ADGroup -Identity $GroupName -ErrorAction Stop
    
    foreach ($Member in (Get-ADGroupMember -Identity $GroupName)) {
        if ($Member.objectClass -eq 'user') {
            $User = Get-ADUser -Identity $Member -Properties Name, EmailAddress, Enabled
            $Members += $User
        } elseif ($Member.objectClass -eq 'group') {
            # Recursively get nested group members
            $Members += Get-ADGroupMembersRecursive -GroupName $Member.Name
        }
    }
    
    return $Members
}

# Usage
Get-ADGroupMembersRecursive -GroupName "Domain Admins" | 
    Select-Object Name, SamAccountName, EmailAddress, Enabled | 
    Sort-Object Name

Simple version (direct members only):

Get-ADGroupMember -Identity "Domain Admins" -Recursive | 
    Where-Object {$_.objectClass -eq 'user'} | 
    Get-ADUser -Properties Name, EmailAddress, Enabled | 
    Select-Object Name, SamAccountName, EmailAddress, Enabled | 
    Sort-Object Name
PowerShellActive DirectoryGroup ManagementSecurity

Identify inactive users for security audits, account cleanup, and compliance reporting

# Find inactive users with comprehensive details
$DaysInactive = 90
$InactiveDate = (Get-Date).AddDays(-$DaysInactive)

Get-ADUser -Filter {LastLogonDate -lt $InactiveDate -and Enabled -eq $true} -Properties Name, SamAccountName, EmailAddress, LastLogonDate, Department, DistinguishedName | 
    Select-Object Name, SamAccountName, EmailAddress, LastLogonDate, Department, DistinguishedName | 
    Sort-Object LastLogonDate

Export inactive users to CSV:

$DaysInactive = 90
$InactiveDate = (Get-Date).AddDays(-$DaysInactive)

Get-ADUser -Filter {LastLogonDate -lt $InactiveDate -and Enabled -eq $true} -Properties Name, SamAccountName, EmailAddress, LastLogonDate, Department | 
    Select-Object Name, SamAccountName, EmailAddress, LastLogonDate, Department | 
    Export-Csv -Path "C:\Reports\InactiveUsers_$DaysInactive days.csv" -NoTypeInformation -Encoding UTF8

Find users who have never logged in:

Get-ADUser -Filter {LastLogonDate -notlike "*" -and Enabled -eq $true} -Properties Name, SamAccountName, WhenCreated, LastLogonDate | 
    Select-Object Name, SamAccountName, WhenCreated, LastLogonDate | 
    Sort-Object WhenCreated
PowerShellActive DirectoryUser ManagementSecurityCompliance

Retrieve Active Directory users with comprehensive property retrieval for enterprise queries

# Search by name pattern with common enterprise properties
Get-ADUser -Filter {Name -like "*John Doe*"} -Properties Name, SamAccountName, EmailAddress, Department, Title, Enabled, LastLogonDate, PasswordLastSet, LockedOut, DistinguishedName | 
    Select-Object Name, SamAccountName, EmailAddress, Department, Title, Enabled, LastLogonDate, PasswordLastSet, LockedOut, DistinguishedName

Get user by exact SamAccountName:

Get-ADUser -Identity "jdoe" -Properties Name, SamAccountName, EmailAddress, Department, Title, Enabled, LastLogonDate, PasswordLastSet, LockedOut, DistinguishedName

Search by email address:

Get-ADUser -Filter {EmailAddress -eq "[email protected]"} -Properties Name, SamAccountName, EmailAddress, Department, Title, Enabled

Search by department:

Get-ADUser -Filter {Department -eq "IT"} -Properties Name, SamAccountName, EmailAddress, Department, Title, Enabled | 
    Sort-Object Name
PowerShellActive DirectoryUser ManagementQuery

Find all disabled user accounts with comprehensive details for security audits and cleanup

# Enterprise audit of disabled accounts
Get-ADUser -Filter {Enabled -eq $false} -Properties Name, SamAccountName, LastLogonDate, WhenChanged, Description, DistinguishedName | 
    Select-Object Name, SamAccountName, LastLogonDate, WhenChanged, Description, DistinguishedName | 
    Sort-Object LastLogonDate -Descending |
    Format-Table -AutoSize

Export disabled users to CSV for review:

Get-ADUser -Filter {Enabled -eq $false} -Properties Name, SamAccountName, LastLogonDate, WhenChanged, DistinguishedName | 
    Select-Object Name, SamAccountName, LastLogonDate, WhenChanged, DistinguishedName | 
    Export-Csv -Path "C:\Reports\DisabledUsers.csv" -NoTypeInformation -Encoding UTF8

Find disabled users not logged in for 90+ days (candidates for deletion):

$CutoffDate = (Get-Date).AddDays(-90)
Get-ADUser -Filter {Enabled -eq $false -and LastLogonDate -lt $CutoffDate} -Properties LastLogonDate |
    Select-Object Name, SamAccountName, LastLogonDate |
    Sort-Object LastLogonDate
PowerShellActive DirectoryUser ManagementSecurityAudit

List computer objects in an OU with comprehensive details for enterprise inventory and compliance

# Get all computers in OU with comprehensive details
Get-ADComputer -Filter * -SearchBase "OU=Workstations,DC=domain,DC=com" -Properties Name, OperatingSystem, OperatingSystemVersion, LastLogonDate, Enabled, Description, DistinguishedName | 
    Select-Object Name, OperatingSystem, OperatingSystemVersion, LastLogonDate, Enabled, Description, DistinguishedName | 
    Sort-Object Name

Export to CSV for inventory:

$OUPath = "OU=Workstations,DC=domain,DC=com"
Get-ADComputer -Filter * -SearchBase $OUPath -Properties Name, OperatingSystem, OperatingSystemVersion, LastLogonDate, Enabled | 
    Select-Object Name, OperatingSystem, OperatingSystemVersion, LastLogonDate, Enabled | 
    Export-Csv -Path "C:\Reports\Computers_$(Get-Date -Format 'yyyyMMdd').csv" -NoTypeInformation -Encoding UTF8

Find computers not logged in for 90+ days:

$CutoffDate = (Get-Date).AddDays(-90)
Get-ADComputer -Filter * -SearchBase "OU=Workstations,DC=domain,DC=com" -Properties LastLogonDate | 
    Where-Object {$_.LastLogonDate -lt $CutoffDate -or $null -eq $_.LastLogonDate} |
    Select-Object Name, LastLogonDate | 
    Sort-Object LastLogonDate
PowerShellActive DirectoryComputer ManagementInventory

List all members of an Active Directory group with comprehensive details for enterprise audits

# Get all members with comprehensive details
Get-ADGroupMember -Identity "Domain Admins" | 
    Get-ADUser -Properties Name, EmailAddress, Enabled, LastLogonDate, PasswordLastSet | 
    Select-Object Name, SamAccountName, EmailAddress, Enabled, LastLogonDate, PasswordLastSet | 
    Sort-Object Name

Export group members to CSV:

$GroupName = "Domain Admins"
Get-ADGroupMember -Identity $GroupName | 
    Get-ADUser -Properties Name, EmailAddress, Enabled, LastLogonDate | 
    Select-Object Name, SamAccountName, EmailAddress, Enabled, LastLogonDate | 
    Export-Csv -Path "C:\Reports\GroupMembers_$GroupName.csv" -NoTypeInformation -Encoding UTF8

Get only enabled members:

Get-ADGroupMember -Identity "Domain Admins" | 
    Get-ADUser -Properties Name, EmailAddress, Enabled | 
    Where-Object {$_.Enabled -eq $true} |
    Select-Object Name, SamAccountName, EmailAddress | 
    Sort-Object Name
PowerShellActive DirectoryGroup ManagementSecurityAudit

Move a user account to a different Organizational Unit with validation

# Move user to different OU with validation
param(
    [Parameter(Mandatory=$true)]
    [string]$SamAccountName,
    
    [Parameter(Mandatory=$true)]
    [string]$TargetOU
)

try {
    # Verify user exists
    $User = Get-ADUser -Identity $SamAccountName -ErrorAction Stop
    
    # Verify target OU exists
    if (-not (Get-ADOrganizationalUnit -Identity $TargetOU -ErrorAction SilentlyContinue)) {
        Write-Error "Target OU $TargetOU does not exist"
        exit 1
    }
    
    # Get current OU
    $CurrentOU = ($User.DistinguishedName -replace '^CN=[^,]+,', '')
    Write-Host "Moving $($User.Name) from $CurrentOU to $TargetOU" -ForegroundColor Yellow
    
    # Move the user
    Move-ADObject -Identity $User.DistinguishedName -TargetPath $TargetOU -ErrorAction Stop
    
    Write-Host "User moved successfully" -ForegroundColor Green
} catch {
    Write-Error "Failed to move user: $($_.Exception.Message)"
    exit 1
}

Quick version:

Move-ADObject -Identity (Get-ADUser -Identity "jdoe").DistinguishedName -TargetPath "OU=Disabled Users,DC=domain,DC=com"
PowerShellActive DirectoryUser ManagementOU Management

Reset a user's password with enterprise security practices and error handling

# Enterprise password reset with validation and logging
param(
    [Parameter(Mandatory=$true)]
    [string]$SamAccountName,
    
    [Parameter(Mandatory=$true)]
    [SecureString]$NewPassword
)

try {
    $user = Get-ADUser -Identity $SamAccountName -ErrorAction Stop
    
    # Reset password
    Set-ADAccountPassword -Identity $SamAccountName -NewPassword $NewPassword -Reset -ErrorAction Stop
    
    # Force password change on next logon
    Set-ADUser -Identity $SamAccountName -ChangePasswordAtLogon $true -ErrorAction Stop
    
    # Log the action (adjust path as needed)
    $logEntry = "$(Get-Date -Format 'yyyy-MM-dd HH:mm:ss') - Password reset for $SamAccountName by $env:USERNAME"
    Add-Content -Path "C:\Logs\PasswordReset.log" -Value $logEntry
    
    Write-Host "Password reset successfully for $($user.Name)" -ForegroundColor Green
} catch {
    Write-Error "Failed to reset password: $($_.Exception.Message)"
    exit 1
}

Enterprise version includes error handling, logging, and parameter validation. For quick reset:

$SecurePassword = ConvertTo-SecureString "TempPassword123!" -AsPlainText -Force
Set-ADAccountPassword -Identity "jdoe" -NewPassword $SecurePassword -Reset
Set-ADUser -Identity "jdoe" -ChangePasswordAtLogon $true
PowerShellActive DirectoryPassword ManagementSecurity

Unlock locked Active Directory accounts with logging and bulk operations support

# Enterprise account unlock with logging
param(
    [Parameter(Mandatory=$true)]
    [string]$SamAccountName
)

try {
    $User = Get-ADUser -Identity $SamAccountName -Properties LockedOut, LastBadPasswordAttempt -ErrorAction Stop
    
    if ($User.LockedOut) {
        Unlock-ADAccount -Identity $SamAccountName -ErrorAction Stop
        
        # Log the unlock action
        $LogEntry = "$(Get-Date -Format 'yyyy-MM-dd HH:mm:ss') - Account unlocked: $SamAccountName by $env:USERNAME (Last bad password attempt: $($User.LastBadPasswordAttempt))"
        Add-Content -Path "C:\Logs\AccountUnlock.log" -Value $LogEntry
        
        Write-Host "Account unlocked successfully for $($User.Name)" -ForegroundColor Green
    } else {
        Write-Host "Account $SamAccountName is not locked" -ForegroundColor Yellow
    }
} catch {
    Write-Error "Failed to unlock account: $($_.Exception.Message)"
    exit 1
}

Check and unlock if locked:

$user = Get-ADUser -Identity "jdoe" -Properties LockedOut
if ($user.LockedOut) {
    Unlock-ADAccount -Identity "jdoe"
    Write-Host "Account unlocked successfully"
}

Bulk unlock from CSV:

$Users = Import-Csv -Path "C:\Data\LockedUsers.csv"
foreach ($User in $Users) {
    try {
        Unlock-ADAccount -Identity $User.SamAccountName -ErrorAction Stop
        Write-Host "Unlocked: $($User.SamAccountName)" -ForegroundColor Green
    } catch {
        Write-Warning "Failed to unlock $($User.SamAccountName): $($_.Exception.Message)"
    }
}
PowerShellActive DirectoryUser ManagementTroubleshootingSecurity