Tutorial

New updates and improvements to Macfleet.

Important notice

The code examples and scripts provided in these tutorials are for educational purposes only. Macfleet is not responsible for any issues, damages, or security vulnerabilities that may arise from the use, modification, or implementation of these examples. Always review and test code in a secure environment before using it in production systems.

Delete Mobile Accounts on macOS Devices

This comprehensive guide demonstrates how to delete mobile accounts on macOS devices for effective user management, device reassignment, and organizational cleanup scenarios.

Overview

Mobile accounts on macOS are user profiles designed for seamless access to resources across different devices within organizations. Unlike local accounts, mobile accounts are centrally managed by directory services like Open Directory or Active Directory, enabling administrators to control access, enforce policies, and manage user data centrally.

Common Scenarios for Mobile Account Deletion

  • Employee departures: Clean up accounts when employees leave the organization
  • Role changes: Remove old mobile accounts when users change positions
  • Device reassignment: Prepare devices for new users
  • Security compliance: Remove inactive or compromised accounts
  • Storage optimization: Free up disk space by removing unused accounts
  • Organizational restructuring: Clean up accounts during company changes

Basic Mobile Account Deletion

Simple Mobile Account Removal Script

Create a basic script to remove all mobile accounts from a macOS device:

#!/bin/bash

# Basic mobile account deletion script
# Usage: ./delete_mobile_accounts.sh

delete_mobile_accounts() {
    echo "Starting mobile account deletion process..."
    
    # Check if running as root
    if [ "$EUID" -ne 0 ]; then
        echo "Error: This script must be run as root"
        exit 1
    fi
    
    # Counter for deleted accounts
    local deleted_count=0
    
    # Loop through all users
    for username in $(dscl . -list /Users | grep -v '^_'); do
        # Check if user has mobile account authentication
        auth_authority=$(dscl . -read "/Users/$username" AuthenticationAuthority 2>/dev/null | grep "LocalCachedUser")
        
        if [ -n "$auth_authority" ]; then
            echo "Removing mobile account: $username"
            
            # Delete user from directory services
            dscl . -delete "/Users/$username"
            
            # Remove user's home directory
            rm -rf "/Users/$username"
            
            ((deleted_count++))
        fi
    done
    
    echo "Mobile accounts removal complete. Deleted $deleted_count accounts."
    echo "Note: Please restart the device for changes to take full effect."
}

# Execute deletion
delete_mobile_accounts

Enhanced Mobile Account Management Script

#!/bin/bash

# Enhanced mobile account management with safety checks and logging
# Usage: ./enhanced_mobile_account_manager.sh

enhanced_mobile_account_manager() {
    local log_file="/var/log/macfleet_mobile_accounts.log"
    local timestamp=$(date '+%Y-%m-%d %H:%M:%S')
    local backup_dir="/var/backups/macfleet/mobile_accounts"
    
    # Check if running as root
    if [ "$EUID" -ne 0 ]; then
        echo "Error: This script must be run as root"
        exit 1
    fi
    
    # Create log directory
    mkdir -p /var/log
    mkdir -p "$backup_dir"
    
    echo "[$timestamp] Enhanced mobile account manager started" >> "$log_file"
    
    # Display current mobile accounts
    display_mobile_accounts
    
    # Confirm deletion
    echo ""
    read -p "Do you want to proceed with mobile account deletion? (y/N): " confirm
    
    if [ "$confirm" = "y" ] || [ "$confirm" = "Y" ]; then
        create_account_backup
        delete_mobile_accounts_enhanced
    else
        echo "Operation cancelled."
        echo "[$timestamp] Mobile account deletion cancelled by user" >> "$log_file"
    fi
}

display_mobile_accounts() {
    echo "======================================="
    echo "Current Mobile Accounts on Device"
    echo "======================================="
    
    local mobile_accounts_found=false
    
    for username in $(dscl . -list /Users | grep -v '^_'); do
        auth_authority=$(dscl . -read "/Users/$username" AuthenticationAuthority 2>/dev/null | grep "LocalCachedUser")
        
        if [ -n "$auth_authority" ]; then
            mobile_accounts_found=true
            
            # Get additional user information
            local real_name=$(dscl . -read "/Users/$username" RealName 2>/dev/null | cut -d: -f2 | xargs)
            local uid=$(dscl . -read "/Users/$username" UniqueID 2>/dev/null | cut -d: -f2 | xargs)
            local home_dir=$(dscl . -read "/Users/$username" NFSHomeDirectory 2>/dev/null | cut -d: -f2 | xargs)
            local last_login=$(last -1 "$username" 2>/dev/null | head -1 | awk '{print $3, $4, $5, $6}')
            
            echo "Username: $username"
            echo "  Real Name: $real_name"
            echo "  UID: $uid"
            echo "  Home Directory: $home_dir"
            echo "  Last Login: $last_login"
            
            # Check home directory size
            if [ -d "$home_dir" ]; then
                local dir_size=$(du -sh "$home_dir" 2>/dev/null | cut -f1)
                echo "  Home Directory Size: $dir_size"
            fi
            
            echo ""
        fi
    done
    
    if [ "$mobile_accounts_found" = false ]; then
        echo "No mobile accounts found on this device."
        echo "[$timestamp] No mobile accounts found on device" >> "$log_file"
        exit 0
    fi
}

create_account_backup() {
    echo "Creating backup of mobile account information..."
    
    local backup_file="$backup_dir/mobile_accounts_backup_$(date +%Y%m%d_%H%M%S).txt"
    
    cat > "$backup_file" << EOF
MacFleet Mobile Account Backup
Generated: $(date)
Device: $(scutil --get ComputerName)
macOS Version: $(sw_vers -productVersion)

Mobile Accounts Found:
EOF
    
    for username in $(dscl . -list /Users | grep -v '^_'); do
        auth_authority=$(dscl . -read "/Users/$username" AuthenticationAuthority 2>/dev/null | grep "LocalCachedUser")
        
        if [ -n "$auth_authority" ]; then
            echo "Username: $username" >> "$backup_file"
            dscl . -read "/Users/$username" >> "$backup_file"
            echo "---" >> "$backup_file"
        fi
    done
    
    echo "Backup created: $backup_file"
    echo "[$timestamp] Mobile account backup created: $backup_file" >> "$log_file"
}

delete_mobile_accounts_enhanced() {
    echo "======================================="
    echo "Deleting Mobile Accounts"
    echo "======================================="
    
    local deleted_count=0
    local failed_count=0
    
    for username in $(dscl . -list /Users | grep -v '^_'); do
        auth_authority=$(dscl . -read "/Users/$username" AuthenticationAuthority 2>/dev/null | grep "LocalCachedUser")
        
        if [ -n "$auth_authority" ]; then
            echo "Processing mobile account: $username"
            
            # Check if user is currently logged in
            if who | grep -q "^$username "; then
                echo "  Warning: User $username is currently logged in. Skipping..."
                echo "[$timestamp] Skipped deletion of $username - user currently logged in" >> "$log_file"
                ((failed_count++))
                continue
            fi
            
            # Delete user from directory services
            if dscl . -delete "/Users/$username" 2>/dev/null; then
                echo "  Deleted user record from directory services"
            else
                echo "  Warning: Failed to delete user record from directory services"
                echo "[$timestamp] Failed to delete user record for $username" >> "$log_file"
                ((failed_count++))
                continue
            fi
            
            # Remove user's home directory
            local home_dir=$(dscl . -read "/Users/$username" NFSHomeDirectory 2>/dev/null | cut -d: -f2 | xargs)
            if [ -d "$home_dir" ]; then
                if rm -rf "$home_dir" 2>/dev/null; then
                    echo "  Removed home directory: $home_dir"
                else
                    echo "  Warning: Failed to remove home directory: $home_dir"
                    echo "[$timestamp] Failed to remove home directory for $username: $home_dir" >> "$log_file"
                fi
            fi
            
            echo "  Successfully deleted mobile account: $username"
            echo "[$timestamp] Successfully deleted mobile account: $username" >> "$log_file"
            ((deleted_count++))
        fi
    done
    
    echo ""
    echo "======================================="
    echo "Mobile Account Deletion Summary"
    echo "======================================="
    echo "Successfully deleted: $deleted_count accounts"
    echo "Failed to delete: $failed_count accounts"
    echo "Total processed: $((deleted_count + failed_count)) accounts"
    echo ""
    echo "Note: Please restart the device for changes to take full effect."
    
    echo "[$timestamp] Mobile account deletion completed - Success: $deleted_count, Failed: $failed_count" >> "$log_file"
}

# Execute enhanced management
enhanced_mobile_account_manager

Advanced Mobile Account Management

Selective Mobile Account Management

#!/bin/bash

# Selective mobile account management system
# Usage: ./selective_mobile_account_manager.sh

selective_mobile_account_manager() {
    local log_file="/var/log/macfleet_selective_mobile_accounts.log"
    local timestamp=$(date '+%Y-%m-%d %H:%M:%S')
    
    # Check if running as root
    if [ "$EUID" -ne 0 ]; then
        echo "Error: This script must be run as root"
        exit 1
    fi
    
    echo "[$timestamp] Selective mobile account manager started" >> "$log_file"
    
    while true; do
        display_selective_menu
        read -p "Select an option (1-7): " choice
        
        case $choice in
            1)
                list_mobile_accounts_detailed
                ;;
            2)
                delete_specific_mobile_account
                ;;
            3)
                delete_inactive_mobile_accounts
                ;;
            4)
                delete_mobile_accounts_by_criteria
                ;;
            5)
                export_mobile_account_report
                ;;
            6)
                restore_mobile_account_backup
                ;;
            7)
                echo "Exiting selective mobile account manager."
                exit 0
                ;;
            *)
                echo "Invalid option. Please try again."
                ;;
        esac
        
        echo ""
        read -p "Press Enter to continue..."
    done
}

display_selective_menu() {
    clear
    echo "======================================="
    echo "MacFleet Selective Mobile Account Manager"
    echo "======================================="
    echo ""
    echo "1. List all mobile accounts with details"
    echo "2. Delete specific mobile account"
    echo "3. Delete inactive mobile accounts"
    echo "4. Delete mobile accounts by criteria"
    echo "5. Export mobile account report"
    echo "6. Restore from backup"
    echo "7. Exit"
    echo ""
}

list_mobile_accounts_detailed() {
    echo "======================================="
    echo "Detailed Mobile Account Information"
    echo "======================================="
    
    local mobile_accounts=()
    local count=0
    
    for username in $(dscl . -list /Users | grep -v '^_'); do
        auth_authority=$(dscl . -read "/Users/$username" AuthenticationAuthority 2>/dev/null | grep "LocalCachedUser")
        
        if [ -n "$auth_authority" ]; then
            mobile_accounts+=("$username")
            ((count++))
            
            echo "[$count] Mobile Account: $username"
            
            # Get detailed information
            local real_name=$(dscl . -read "/Users/$username" RealName 2>/dev/null | cut -d: -f2 | xargs)
            local uid=$(dscl . -read "/Users/$username" UniqueID 2>/dev/null | cut -d: -f2 | xargs)
            local gid=$(dscl . -read "/Users/$username" PrimaryGroupID 2>/dev/null | cut -d: -f2 | xargs)
            local home_dir=$(dscl . -read "/Users/$username" NFSHomeDirectory 2>/dev/null | cut -d: -f2 | xargs)
            local shell=$(dscl . -read "/Users/$username" UserShell 2>/dev/null | cut -d: -f2 | xargs)
            
            echo "    Real Name: $real_name"
            echo "    UID: $uid"
            echo "    GID: $gid"
            echo "    Home Directory: $home_dir"
            echo "    Shell: $shell"
            
            # Check if user is currently logged in
            if who | grep -q "^$username "; then
                echo "    Status: Currently logged in"
            else
                echo "    Status: Not logged in"
            fi
            
            # Get last login information
            local last_login=$(last -1 "$username" 2>/dev/null | head -1)
            if [ -n "$last_login" ]; then
                echo "    Last Login: $last_login"
            else
                echo "    Last Login: Never"
            fi
            
            # Check home directory size
            if [ -d "$home_dir" ]; then
                local dir_size=$(du -sh "$home_dir" 2>/dev/null | cut -f1)
                echo "    Home Directory Size: $dir_size"
                
                # Check last modification time
                local last_modified=$(stat -f "%Sm" "$home_dir" 2>/dev/null)
                echo "    Last Modified: $last_modified"
            else
                echo "    Home Directory: Not found"
            fi
            
            echo ""
        fi
    done
    
    if [ $count -eq 0 ]; then
        echo "No mobile accounts found on this device."
    else
        echo "Total mobile accounts found: $count"
    fi
}

delete_specific_mobile_account() {
    echo "======================================="
    echo "Delete Specific Mobile Account"
    echo "======================================="
    
    # List mobile accounts with numbers
    local mobile_accounts=()
    local count=0
    
    for username in $(dscl . -list /Users | grep -v '^_'); do
        auth_authority=$(dscl . -read "/Users/$username" AuthenticationAuthority 2>/dev/null | grep "LocalCachedUser")
        
        if [ -n "$auth_authority" ]; then
            mobile_accounts+=("$username")
            ((count++))
            echo "[$count] $username"
        fi
    done
    
    if [ $count -eq 0 ]; then
        echo "No mobile accounts found on this device."
        return
    fi
    
    echo ""
    read -p "Enter the number of the account to delete (1-$count): " selection
    
    if [[ "$selection" =~ ^[0-9]+$ ]] && [ "$selection" -ge 1 ] && [ "$selection" -le $count ]; then
        local selected_user="${mobile_accounts[$((selection-1))]}"
        
        echo ""
        echo "Selected account: $selected_user"
        
        # Show account details
        local real_name=$(dscl . -read "/Users/$selected_user" RealName 2>/dev/null | cut -d: -f2 | xargs)
        local home_dir=$(dscl . -read "/Users/$selected_user" NFSHomeDirectory 2>/dev/null | cut -d: -f2 | xargs)
        
        echo "Real Name: $real_name"
        echo "Home Directory: $home_dir"
        
        # Check if user is logged in
        if who | grep -q "^$selected_user "; then
            echo "Warning: User is currently logged in!"
            read -p "Do you want to continue anyway? (y/N): " force_delete
            if [ "$force_delete" != "y" ] && [ "$force_delete" != "Y" ]; then
                echo "Deletion cancelled."
                return
            fi
        fi
        
        echo ""
        read -p "Are you sure you want to delete this account? (y/N): " confirm
        
        if [ "$confirm" = "y" ] || [ "$confirm" = "Y" ]; then
            delete_single_mobile_account "$selected_user"
        else
            echo "Deletion cancelled."
        fi
    else
        echo "Invalid selection."
    fi
}

delete_single_mobile_account() {
    local username="$1"
    
    echo "Deleting mobile account: $username"
    
    # Create backup of user data
    local backup_dir="/var/backups/macfleet/mobile_accounts"
    mkdir -p "$backup_dir"
    
    local backup_file="$backup_dir/${username}_backup_$(date +%Y%m%d_%H%M%S).txt"
    
    echo "Creating backup of user data..."
    dscl . -read "/Users/$username" > "$backup_file"
    
    # Delete user from directory services
    if dscl . -delete "/Users/$username" 2>/dev/null; then
        echo "User record deleted from directory services"
    else
        echo "Failed to delete user record from directory services"
        return 1
    fi
    
    # Remove user's home directory
    local home_dir=$(dscl . -read "/Users/$username" NFSHomeDirectory 2>/dev/null | cut -d: -f2 | xargs)
    if [ -d "$home_dir" ]; then
        read -p "Do you want to remove the home directory? (y/N): " remove_home
        if [ "$remove_home" = "y" ] || [ "$remove_home" = "Y" ]; then
            if rm -rf "$home_dir"; then
                echo "Home directory removed: $home_dir"
            else
                echo "Failed to remove home directory: $home_dir"
            fi
        else
            echo "Home directory preserved: $home_dir"
        fi
    fi
    
    echo "Successfully deleted mobile account: $username"
    echo "Backup created: $backup_file"
    echo "[$timestamp] Successfully deleted mobile account: $username" >> "$log_file"
}

delete_inactive_mobile_accounts() {
    echo "======================================="
    echo "Delete Inactive Mobile Accounts"
    echo "======================================="
    
    read -p "Enter number of days since last login to consider inactive (default: 30): " days_inactive
    days_inactive=${days_inactive:-30}
    
    echo "Searching for mobile accounts inactive for more than $days_inactive days..."
    
    local inactive_accounts=()
    local current_timestamp=$(date +%s)
    local cutoff_timestamp=$((current_timestamp - (days_inactive * 24 * 60 * 60)))
    
    for username in $(dscl . -list /Users | grep -v '^_'); do
        auth_authority=$(dscl . -read "/Users/$username" AuthenticationAuthority 2>/dev/null | grep "LocalCachedUser")
        
        if [ -n "$auth_authority" ]; then
            # Check last login
            local last_login=$(last -1 "$username" 2>/dev/null | head -1 | awk '{print $3, $4, $5, $6}')
            
            if [ -n "$last_login" ]; then
                local last_login_timestamp=$(date -j -f "%a %b %d %H:%M:%S %Y" "$last_login" +%s 2>/dev/null)
                
                if [ -n "$last_login_timestamp" ] && [ "$last_login_timestamp" -lt "$cutoff_timestamp" ]; then
                    inactive_accounts+=("$username")
                    echo "Inactive account found: $username (last login: $last_login)"
                fi
            else
                # No login record found - consider as inactive
                inactive_accounts+=("$username")
                echo "Inactive account found: $username (no login record)"
            fi
        fi
    done
    
    if [ ${#inactive_accounts[@]} -eq 0 ]; then
        echo "No inactive mobile accounts found."
        return
    fi
    
    echo ""
    echo "Found ${#inactive_accounts[@]} inactive mobile accounts."
    read -p "Do you want to delete all inactive accounts? (y/N): " confirm
    
    if [ "$confirm" = "y" ] || [ "$confirm" = "Y" ]; then
        for username in "${inactive_accounts[@]}"; do
            echo "Deleting inactive account: $username"
            delete_single_mobile_account "$username"
        done
        echo "Inactive mobile accounts deletion completed."
    else
        echo "Deletion cancelled."
    fi
}

delete_mobile_accounts_by_criteria() {
    echo "======================================="
    echo "Delete Mobile Accounts by Criteria"
    echo "======================================="
    
    echo "Available criteria:"
    echo "1. By UID range"
    echo "2. By home directory pattern"
    echo "3. By real name pattern"
    echo "4. By last login date"
    echo ""
    read -p "Select criteria (1-4): " criteria
    
    case $criteria in
        1)
            delete_by_uid_range
            ;;
        2)
            delete_by_home_pattern
            ;;
        3)
            delete_by_name_pattern
            ;;
        4)
            delete_by_login_date
            ;;
        *)
            echo "Invalid criteria selected."
            ;;
    esac
}

delete_by_uid_range() {
    read -p "Enter minimum UID: " min_uid
    read -p "Enter maximum UID: " max_uid
    
    echo "Searching for mobile accounts with UID between $min_uid and $max_uid..."
    
    local matching_accounts=()
    
    for username in $(dscl . -list /Users | grep -v '^_'); do
        auth_authority=$(dscl . -read "/Users/$username" AuthenticationAuthority 2>/dev/null | grep "LocalCachedUser")
        
        if [ -n "$auth_authority" ]; then
            local uid=$(dscl . -read "/Users/$username" UniqueID 2>/dev/null | cut -d: -f2 | xargs)
            
            if [ "$uid" -ge "$min_uid" ] && [ "$uid" -le "$max_uid" ]; then
                matching_accounts+=("$username")
                echo "Found matching account: $username (UID: $uid)"
            fi
        fi
    done
    
    if [ ${#matching_accounts[@]} -eq 0 ]; then
        echo "No mobile accounts found matching the UID criteria."
        return
    fi
    
    echo ""
    echo "Found ${#matching_accounts[@]} matching mobile accounts."
    read -p "Do you want to delete all matching accounts? (y/N): " confirm
    
    if [ "$confirm" = "y" ] || [ "$confirm" = "Y" ]; then
        for username in "${matching_accounts[@]}"; do
            delete_single_mobile_account "$username"
        done
        echo "Mobile accounts deletion by UID range completed."
    else
        echo "Deletion cancelled."
    fi
}

delete_by_home_pattern() {
    read -p "Enter home directory pattern (e.g., /Users/temp*): " pattern
    
    echo "Searching for mobile accounts with home directory matching pattern: $pattern"
    
    local matching_accounts=()
    
    for username in $(dscl . -list /Users | grep -v '^_'); do
        auth_authority=$(dscl . -read "/Users/$username" AuthenticationAuthority 2>/dev/null | grep "LocalCachedUser")
        
        if [ -n "$auth_authority" ]; then
            local home_dir=$(dscl . -read "/Users/$username" NFSHomeDirectory 2>/dev/null | cut -d: -f2 | xargs)
            
            if [[ "$home_dir" == $pattern ]]; then
                matching_accounts+=("$username")
                echo "Found matching account: $username (Home: $home_dir)"
            fi
        fi
    done
    
    if [ ${#matching_accounts[@]} -eq 0 ]; then
        echo "No mobile accounts found matching the home directory pattern."
        return
    fi
    
    echo ""
    echo "Found ${#matching_accounts[@]} matching mobile accounts."
    read -p "Do you want to delete all matching accounts? (y/N): " confirm
    
    if [ "$confirm" = "y" ] || [ "$confirm" = "Y" ]; then
        for username in "${matching_accounts[@]}"; do
            delete_single_mobile_account "$username"
        done
        echo "Mobile accounts deletion by home directory pattern completed."
    else
        echo "Deletion cancelled."
    fi
}

delete_by_name_pattern() {
    read -p "Enter real name pattern (e.g., *Test*): " pattern
    
    echo "Searching for mobile accounts with real name matching pattern: $pattern"
    
    local matching_accounts=()
    
    for username in $(dscl . -list /Users | grep -v '^_'); do
        auth_authority=$(dscl . -read "/Users/$username" AuthenticationAuthority 2>/dev/null | grep "LocalCachedUser")
        
        if [ -n "$auth_authority" ]; then
            local real_name=$(dscl . -read "/Users/$username" RealName 2>/dev/null | cut -d: -f2 | xargs)
            
            if [[ "$real_name" == $pattern ]]; then
                matching_accounts+=("$username")
                echo "Found matching account: $username (Real Name: $real_name)"
            fi
        fi
    done
    
    if [ ${#matching_accounts[@]} -eq 0 ]; then
        echo "No mobile accounts found matching the real name pattern."
        return
    fi
    
    echo ""
    echo "Found ${#matching_accounts[@]} matching mobile accounts."
    read -p "Do you want to delete all matching accounts? (y/N): " confirm
    
    if [ "$confirm" = "y" ] || [ "$confirm" = "Y" ]; then
        for username in "${matching_accounts[@]}"; do
            delete_single_mobile_account "$username"
        done
        echo "Mobile accounts deletion by real name pattern completed."
    else
        echo "Deletion cancelled."
    fi
}

delete_by_login_date() {
    read -p "Enter cutoff date (YYYY-MM-DD): " cutoff_date
    
    local cutoff_timestamp=$(date -j -f "%Y-%m-%d" "$cutoff_date" +%s 2>/dev/null)
    
    if [ -z "$cutoff_timestamp" ]; then
        echo "Invalid date format. Please use YYYY-MM-DD format."
        return
    fi
    
    echo "Searching for mobile accounts with last login before $cutoff_date..."
    
    local matching_accounts=()
    
    for username in $(dscl . -list /Users | grep -v '^_'); do
        auth_authority=$(dscl . -read "/Users/$username" AuthenticationAuthority 2>/dev/null | grep "LocalCachedUser")
        
        if [ -n "$auth_authority" ]; then
            local last_login=$(last -1 "$username" 2>/dev/null | head -1 | awk '{print $3, $4, $5, $6}')
            
            if [ -n "$last_login" ]; then
                local last_login_timestamp=$(date -j -f "%a %b %d %H:%M:%S %Y" "$last_login" +%s 2>/dev/null)
                
                if [ -n "$last_login_timestamp" ] && [ "$last_login_timestamp" -lt "$cutoff_timestamp" ]; then
                    matching_accounts+=("$username")
                    echo "Found matching account: $username (last login: $last_login)"
                fi
            else
                # No login record - consider as before cutoff
                matching_accounts+=("$username")
                echo "Found matching account: $username (no login record)"
            fi
        fi
    done
    
    if [ ${#matching_accounts[@]} -eq 0 ]; then
        echo "No mobile accounts found with last login before $cutoff_date."
        return
    fi
    
    echo ""
    echo "Found ${#matching_accounts[@]} matching mobile accounts."
    read -p "Do you want to delete all matching accounts? (y/N): " confirm
    
    if [ "$confirm" = "y" ] || [ "$confirm" = "Y" ]; then
        for username in "${matching_accounts[@]}"; do
            delete_single_mobile_account "$username"
        done
        echo "Mobile accounts deletion by login date completed."
    else
        echo "Deletion cancelled."
    fi
}

export_mobile_account_report() {
    echo "======================================="
    echo "Export Mobile Account Report"
    echo "======================================="
    
    local report_file="/tmp/mobile_accounts_report_$(date +%Y%m%d_%H%M%S).txt"
    
    cat > "$report_file" << EOF
MacFleet Mobile Account Report
Generated: $(date)
Device: $(scutil --get ComputerName)
macOS Version: $(sw_vers -productVersion)

Mobile Accounts Summary:
EOF
    
    local count=0
    for username in $(dscl . -list /Users | grep -v '^_'); do
        auth_authority=$(dscl . -read "/Users/$username" AuthenticationAuthority 2>/dev/null | grep "LocalCachedUser")
        
        if [ -n "$auth_authority" ]; then
            ((count++))
            
            echo "" >> "$report_file"
            echo "[$count] Username: $username" >> "$report_file"
            
            # Get detailed information
            local real_name=$(dscl . -read "/Users/$username" RealName 2>/dev/null | cut -d: -f2 | xargs)
            local uid=$(dscl . -read "/Users/$username" UniqueID 2>/dev/null | cut -d: -f2 | xargs)
            local home_dir=$(dscl . -read "/Users/$username" NFSHomeDirectory 2>/dev/null | cut -d: -f2 | xargs)
            local last_login=$(last -1 "$username" 2>/dev/null | head -1)
            
            echo "    Real Name: $real_name" >> "$report_file"
            echo "    UID: $uid" >> "$report_file"
            echo "    Home Directory: $home_dir" >> "$report_file"
            echo "    Last Login: $last_login" >> "$report_file"
            
            # Check if user is logged in
            if who | grep -q "^$username "; then
                echo "    Status: Currently logged in" >> "$report_file"
            else
                echo "    Status: Not logged in" >> "$report_file"
            fi
            
            # Check home directory size
            if [ -d "$home_dir" ]; then
                local dir_size=$(du -sh "$home_dir" 2>/dev/null | cut -f1)
                echo "    Home Directory Size: $dir_size" >> "$report_file"
            fi
        fi
    done
    
    echo "" >> "$report_file"
    echo "Total Mobile Accounts: $count" >> "$report_file"
    
    echo "Mobile account report exported to: $report_file"
}

restore_mobile_account_backup() {
    echo "======================================="
    echo "Restore Mobile Account Backup"
    echo "======================================="
    
    local backup_dir="/var/backups/macfleet/mobile_accounts"
    
    if [ ! -d "$backup_dir" ]; then
        echo "No backup directory found: $backup_dir"
        return
    fi
    
    echo "Available backups:"
    ls -la "$backup_dir"/*.txt 2>/dev/null || echo "No backup files found."
    
    echo ""
    read -p "Enter the backup filename to restore: " backup_file
    
    if [ -f "$backup_dir/$backup_file" ]; then
        echo "Backup file found: $backup_dir/$backup_file"
        echo "Note: This feature shows backup content for reference."
        echo "Manual restoration may be required for complex scenarios."
        echo ""
        cat "$backup_dir/$backup_file"
    else
        echo "Backup file not found: $backup_dir/$backup_file"
    fi
}

# Execute selective management
selective_mobile_account_manager

Enterprise Mobile Account Management

Automated Mobile Account Cleanup

#!/bin/bash

# Automated mobile account cleanup for enterprise environments
# Usage: ./automated_mobile_cleanup.sh

automated_mobile_cleanup() {
    local config_file="/etc/macfleet/mobile_cleanup_config.conf"
    local log_file="/var/log/macfleet_automated_cleanup.log"
    local timestamp=$(date '+%Y-%m-%d %H:%M:%S')
    
    # Check if running as root
    if [ "$EUID" -ne 0 ]; then
        echo "Error: This script must be run as root"
        exit 1
    fi
    
    # Create configuration if it doesn't exist
    if [ ! -f "$config_file" ]; then
        create_cleanup_config
    fi
    
    source "$config_file"
    
    echo "[$timestamp] Automated mobile account cleanup started" >> "$log_file"
    
    # Execute cleanup based on configuration
    execute_automated_cleanup
}

create_cleanup_config() {
    mkdir -p /etc/macfleet
    
    cat > "/etc/macfleet/mobile_cleanup_config.conf" << 'EOF'
# MacFleet Automated Mobile Account Cleanup Configuration

# Organization settings
ORGANIZATION_NAME="MacFleet Organization"
IT_CONTACT="support@macfleet.com"

# Cleanup criteria
CLEANUP_INACTIVE_DAYS="30"
CLEANUP_ENABLED="true"
PRESERVE_ADMIN_ACCOUNTS="true"

# Safety settings
REQUIRE_CONFIRMATION="true"
CREATE_BACKUP="true"
PRESERVE_HOME_DATA="false"
SKIP_LOGGED_IN_USERS="true"

# Notification settings
SEND_NOTIFICATIONS="true"
NOTIFICATION_EMAIL="admin@macfleet.com"

# Scheduling
ENABLE_SCHEDULED_CLEANUP="false"
CLEANUP_SCHEDULE="weekly"
CLEANUP_TIME="02:00"

# Logging
ENABLE_DETAILED_LOGGING="true"
LOG_RETENTION_DAYS="90"
EOF
    
    echo "Cleanup configuration created at /etc/macfleet/mobile_cleanup_config.conf"
}

execute_automated_cleanup() {
    echo "[$timestamp] Executing automated mobile account cleanup" >> "$log_file"
    
    # Check if cleanup is enabled
    if [ "$CLEANUP_ENABLED" != "true" ]; then
        echo "[$timestamp] Automated cleanup is disabled" >> "$log_file"
        echo "Automated cleanup is disabled in configuration."
        return
    fi
    
    # Display cleanup configuration
    echo "======================================="
    echo "MacFleet Automated Mobile Account Cleanup"
    echo "======================================="
    echo "Organization: $ORGANIZATION_NAME"
    echo "Cleanup inactive accounts older than: $CLEANUP_INACTIVE_DAYS days"
    echo "Preserve admin accounts: $PRESERVE_ADMIN_ACCOUNTS"
    echo "Create backup: $CREATE_BACKUP"
    echo "Skip logged in users: $SKIP_LOGGED_IN_USERS"
    echo ""
    
    # Require confirmation if enabled
    if [ "$REQUIRE_CONFIRMATION" = "true" ]; then
        read -p "Do you want to proceed with automated cleanup? (y/N): " confirm
        if [ "$confirm" != "y" ] && [ "$confirm" != "Y" ]; then
            echo "[$timestamp] Automated cleanup cancelled by user" >> "$log_file"
            echo "Automated cleanup cancelled."
            return
        fi
    fi
    
    # Find accounts to cleanup
    local accounts_to_cleanup=()
    local current_timestamp=$(date +%s)
    local cutoff_timestamp=$((current_timestamp - (CLEANUP_INACTIVE_DAYS * 24 * 60 * 60)))
    
    echo "Scanning for mobile accounts to cleanup..."
    
    for username in $(dscl . -list /Users | grep -v '^_'); do
        auth_authority=$(dscl . -read "/Users/$username" AuthenticationAuthority 2>/dev/null | grep "LocalCachedUser")
        
        if [ -n "$auth_authority" ]; then
            local should_cleanup=true
            
            # Check if user is admin (if preservation is enabled)
            if [ "$PRESERVE_ADMIN_ACCOUNTS" = "true" ]; then
                if dscl . -read "/Groups/admin" GroupMembership 2>/dev/null | grep -q "$username"; then
                    echo "Skipping admin account: $username"
                    echo "[$timestamp] Skipped admin account: $username" >> "$log_file"
                    should_cleanup=false
                fi
            fi
            
            # Check if user is logged in (if skip is enabled)
            if [ "$SKIP_LOGGED_IN_USERS" = "true" ] && who | grep -q "^$username "; then
                echo "Skipping logged in user: $username"
                echo "[$timestamp] Skipped logged in user: $username" >> "$log_file"
                should_cleanup=false
            fi
            
            # Check last login date
            if [ "$should_cleanup" = true ]; then
                local last_login=$(last -1 "$username" 2>/dev/null | head -1 | awk '{print $3, $4, $5, $6}')
                
                if [ -n "$last_login" ]; then
                    local last_login_timestamp=$(date -j -f "%a %b %d %H:%M:%S %Y" "$last_login" +%s 2>/dev/null)
                    
                    if [ -n "$last_login_timestamp" ] && [ "$last_login_timestamp" -lt "$cutoff_timestamp" ]; then
                        accounts_to_cleanup+=("$username")
                        echo "Account marked for cleanup: $username (last login: $last_login)"
                    fi
                else
                    # No login record - consider for cleanup
                    accounts_to_cleanup+=("$username")
                    echo "Account marked for cleanup: $username (no login record)"
                fi
            fi
        fi
    done
    
    if [ ${#accounts_to_cleanup[@]} -eq 0 ]; then
        echo "No mobile accounts found that meet cleanup criteria."
        echo "[$timestamp] No mobile accounts found for cleanup" >> "$log_file"
        return
    fi
    
    echo ""
    echo "Found ${#accounts_to_cleanup[@]} mobile accounts for cleanup:"
    for account in "${accounts_to_cleanup[@]}"; do
        echo "  - $account"
    done
    
    # Create backup if enabled
    if [ "$CREATE_BACKUP" = "true" ]; then
        create_automated_backup "${accounts_to_cleanup[@]}"
    fi
    
    # Cleanup accounts
    local success_count=0
    local failure_count=0
    
    echo ""
    echo "Starting automated cleanup..."
    
    for username in "${accounts_to_cleanup[@]}"; do
        echo "Processing: $username"
        
        # Delete user from directory services
        if dscl . -delete "/Users/$username" 2>/dev/null; then
            echo "  Deleted user record from directory services"
            
            # Handle home directory based on configuration
            local home_dir=$(dscl . -read "/Users/$username" NFSHomeDirectory 2>/dev/null | cut -d: -f2 | xargs)
            
            if [ -d "$home_dir" ]; then
                if [ "$PRESERVE_HOME_DATA" = "true" ]; then
                    echo "  Preserved home directory: $home_dir"
                else
                    if rm -rf "$home_dir" 2>/dev/null; then
                        echo "  Removed home directory: $home_dir"
                    else
                        echo "  Warning: Failed to remove home directory: $home_dir"
                    fi
                fi
            fi
            
            echo "  Successfully cleaned up account: $username"
            echo "[$timestamp] Successfully cleaned up account: $username" >> "$log_file"
            ((success_count++))
        else
            echo "  Failed to cleanup account: $username"
            echo "[$timestamp] Failed to cleanup account: $username" >> "$log_file"
            ((failure_count++))
        fi
    done
    
    # Generate cleanup summary
    echo ""
    echo "======================================="
    echo "Automated Cleanup Summary"
    echo "======================================="
    echo "Total accounts processed: ${#accounts_to_cleanup[@]}"
    echo "Successfully cleaned up: $success_count"
    echo "Failed to cleanup: $failure_count"
    echo "Cleanup completed at: $(date)"
    
    echo "[$timestamp] Automated cleanup completed - Success: $success_count, Failed: $failure_count" >> "$log_file"
    
    # Send notification if enabled
    if [ "$SEND_NOTIFICATIONS" = "true" ]; then
        send_cleanup_notification "$success_count" "$failure_count"
    fi
    
    echo ""
    echo "Note: Please restart the device for changes to take full effect."
}

create_automated_backup() {
    local accounts=("$@")
    local backup_dir="/var/backups/macfleet/automated_cleanup"
    local backup_file="$backup_dir/cleanup_backup_$(date +%Y%m%d_%H%M%S).txt"
    
    mkdir -p "$backup_dir"
    
    echo "Creating backup of accounts to be cleaned up..."
    
    cat > "$backup_file" << EOF
MacFleet Automated Cleanup Backup
Generated: $(date)
Device: $(scutil --get ComputerName)
Organization: $ORGANIZATION_NAME
Cleanup Criteria: Inactive for $CLEANUP_INACTIVE_DAYS days

Accounts to be cleaned up:
EOF
    
    for username in "${accounts[@]}"; do
        echo "" >> "$backup_file"
        echo "Username: $username" >> "$backup_file"
        dscl . -read "/Users/$username" >> "$backup_file" 2>/dev/null
        echo "---" >> "$backup_file"
    done
    
    echo "Backup created: $backup_file"
    echo "[$timestamp] Automated cleanup backup created: $backup_file" >> "$log_file"
}

send_cleanup_notification() {
    local success_count=$1
    local failure_count=$2
    
    local notification_subject="MacFleet Mobile Account Cleanup Report"
    local notification_body="Automated mobile account cleanup completed.

Device: $(scutil --get ComputerName)
Organization: $ORGANIZATION_NAME
Cleanup Date: $(date)

Results:
- Successfully cleaned up: $success_count accounts
- Failed to cleanup: $failure_count accounts
- Total processed: $((success_count + failure_count)) accounts

For detailed logs, check: /var/log/macfleet_automated_cleanup.log

Contact: $IT_CONTACT"
    
    # Use osascript to display notification (for local notifications)
    osascript -e "display notification \"Cleanup completed: $success_count success, $failure_count failed\" with title \"MacFleet Mobile Account Cleanup\""
    
    echo "[$timestamp] Cleanup notification sent" >> "$log_file"
}

# Execute automated cleanup
automated_mobile_cleanup

Troubleshooting and Best Practices

Common Issues and Solutions

  1. Permission Errors: Always run scripts as root using sudo
  2. Logged-in Users: Check for active sessions before deletion
  3. Directory Services: Verify mobile account identification using LocalCachedUser attribute
  4. Home Directory Protection: Create backups before removing home directories
  5. Network Accounts: Ensure network connectivity for directory service operations

Best Practices

  • Test First: Always test scripts in controlled environments
  • Create Backups: Maintain backups of user data before deletion
  • Log Operations: Keep detailed logs of all account operations
  • User Communication: Notify users before account cleanup
  • Schedule Maintenance: Perform cleanup during maintenance windows

Conclusion

Mobile account management is crucial for maintaining clean and secure macOS environments. These scripts provide comprehensive solutions for deleting mobile accounts, from simple cleanup to enterprise-grade automation. Always ensure proper testing and backup procedures before implementing in production environments.

Tutorial

New updates and improvements to Macfleet.

Wi-Fi Network Management on macOS

Deploy and manage comprehensive Wi-Fi network configurations across your MacFleet devices. This tutorial covers network policy management, security configurations, proxy settings, DNS management, and enterprise-grade network deployment strategies.

Understanding macOS Network Management

macOS provides powerful command-line tools for network management:

  • networksetup - Primary tool for network configuration
  • airport - Advanced Wi-Fi scanning and management
  • scutil - System configuration utility for network settings
  • Network profiles - Enterprise policy-based network management

Basic Wi-Fi Operations

Enable/Disable Wi-Fi Interface

#!/bin/bash

# Enable Wi-Fi interface
enable_wifi() {
    echo "Enabling Wi-Fi interface..."
    networksetup -setairportpower en0 on
    
    if [[ $? -eq 0 ]]; then
        echo "✅ Wi-Fi interface enabled successfully"
        return 0
    else
        echo "❌ Failed to enable Wi-Fi interface"
        return 1
    fi
}

# Disable Wi-Fi interface
disable_wifi() {
    echo "⚠️  Disabling Wi-Fi interface..."
    echo "Ensure device has alternative connectivity (Ethernet, etc.)"
    
    networksetup -setairportpower en0 off
    
    if [[ $? -eq 0 ]]; then
        echo "✅ Wi-Fi interface disabled successfully"
        return 0
    else
        echo "❌ Failed to disable Wi-Fi interface"
        return 1
    fi
}

# Usage
enable_wifi
# disable_wifi

Turn Wi-Fi Service On/Off

#!/bin/bash

# Turn Wi-Fi service on (user can still control from menu bar)
turn_wifi_on() {
    echo "Turning Wi-Fi service on..."
    networksetup -setnetworkserviceenabled Wi-Fi on
    
    if [[ $? -eq 0 ]]; then
        echo "✅ Wi-Fi service turned on"
        return 0
    else
        echo "❌ Failed to turn Wi-Fi service on"
        return 1
    fi
}

# Turn Wi-Fi service off (user can still control from menu bar)
turn_wifi_off() {
    echo "Turning Wi-Fi service off..."
    networksetup -setnetworkserviceenabled Wi-Fi off
    
    if [[ $? -eq 0 ]]; then
        echo "✅ Wi-Fi service turned off"
        return 0
    else
        echo "❌ Failed to turn Wi-Fi service off"
        return 1
    fi
}

# Check Wi-Fi service status
check_wifi_service() {
    echo "Checking Wi-Fi service status..."
    local status
    status=$(networksetup -getnetworkserviceenabled Wi-Fi)
    
    echo "Wi-Fi service status: $status"
    return 0
}

# Usage
check_wifi_service
turn_wifi_on

Wi-Fi Network Information

Get Current Network Information

#!/bin/bash

# Get current Wi-Fi network SSID
get_current_network() {
    echo "=== Current Wi-Fi Network ==="
    local network_info
    network_info=$(networksetup -getairportnetwork en0)
    
    if [[ "$network_info" == *"not associated"* ]]; then
        echo "❌ Not connected to any Wi-Fi network"
        return 1
    else
        echo "📶 $network_info"
        return 0
    fi
}

# Get comprehensive Wi-Fi information
get_wifi_info() {
    echo "=== Wi-Fi Network Information ==="
    networksetup -getinfo Wi-Fi
    
    echo -e "\n=== Wi-Fi Interface Details ==="
    ifconfig en0 | grep -E "(inet |ether |status)"
    
    echo -e "\n=== Wi-Fi Quality ==="
    /System/Library/PrivateFrameworks/Apple80211.framework/Versions/Current/Resources/airport -I
}

# Get available networks
scan_networks() {
    echo "=== Available Wi-Fi Networks ==="
    /System/Library/PrivateFrameworks/Apple80211.framework/Versions/Current/Resources/airport -s
}

# Usage
get_current_network
echo ""
get_wifi_info
echo ""
scan_networks

Advanced Network Diagnostics

#!/bin/bash

# Comprehensive network diagnostics
network_diagnostics() {
    echo "=== MacFleet Network Diagnostics ==="
    echo "Timestamp: $(date)"
    echo "Hostname: $(hostname)"
    echo "======================================="
    
    # Wi-Fi interface status
    echo -e "\n🔍 Wi-Fi Interface Status:"
    local wifi_power
    wifi_power=$(networksetup -getairportpower en0)
    echo "Power: $wifi_power"
    
    local wifi_service
    wifi_service=$(networksetup -getnetworkserviceenabled Wi-Fi)
    echo "Service: $wifi_service"
    
    # Current connection
    echo -e "\n📶 Current Connection:"
    networksetup -getairportnetwork en0
    
    # Network configuration
    echo -e "\n⚙️  Network Configuration:"
    networksetup -getinfo Wi-Fi
    
    # DNS settings
    echo -e "\n🌐 DNS Settings:"
    networksetup -getdnsservers Wi-Fi
    
    # Proxy settings
    echo -e "\n🔒 Proxy Settings:"
    networksetup -getwebproxy Wi-Fi
    networksetup -getsecurewebproxy Wi-Fi
    networksetup -getautoproxyurl Wi-Fi
    
    # Signal quality
    echo -e "\n📊 Signal Quality:"
    /System/Library/PrivateFrameworks/Apple80211.framework/Versions/Current/Resources/airport -I | grep -E "(SSID|BSSID|RSSI|noise|CC|channel)"
    
    # Connectivity test
    echo -e "\n🌍 Connectivity Test:"
    if ping -c 3 8.8.8.8 >/dev/null 2>&1; then
        echo "✅ Internet connectivity: Available"
    else
        echo "❌ Internet connectivity: Failed"
    fi
    
    if ping -c 3 apple.com >/dev/null 2>&1; then
        echo "✅ DNS resolution: Working"
    else
        echo "❌ DNS resolution: Failed"
    fi
}

# Generate network report
generate_network_report() {
    local report_file="/tmp/network_report_$(date +%Y%m%d_%H%M%S).txt"
    
    echo "Generating network report: $report_file"
    network_diagnostics > "$report_file"
    
    echo "📄 Network report saved: $report_file"
    return 0
}

# Usage
network_diagnostics

Enterprise Wi-Fi Management System

#!/bin/bash

# MacFleet Enterprise Wi-Fi Management System
# Centralized Wi-Fi configuration and policy management for fleet devices

# Configuration
LOG_FILE="/var/log/macfleet_wifi.log"
CONFIG_DIR="/etc/macfleet/wifi"
PROFILES_DIR="$CONFIG_DIR/profiles"
POLICIES_DIR="$CONFIG_DIR/policies"
BACKUP_DIR="/var/backups/network_configs"

# Network profile templates
declare -A NETWORK_PROFILES=(
    ["corporate"]="security=WPA2Enterprise,proxy=auto,dns=corporate"
    ["guest"]="security=WPA2Personal,proxy=none,dns=public"
    ["secure"]="security=WPA2Enterprise,proxy=mandatory,dns=secure"
    ["development"]="security=WPA2Personal,proxy=bypass,dns=dev"
    ["public"]="security=none,proxy=auto,dns=public"
)

# DNS server configurations
declare -A DNS_CONFIGS=(
    ["corporate"]="10.0.1.1 10.0.1.2"
    ["public"]="8.8.8.8 8.8.4.4"
    ["secure"]="1.1.1.1 1.0.0.1"
    ["dev"]="192.168.1.1 8.8.8.8"
)

# Proxy configurations
declare -A PROXY_CONFIGS=(
    ["corporate_web"]="proxy.company.com:8080:authenticated"
    ["corporate_auto"]="http://proxy.company.com/proxy.pac"
    ["guest_web"]="guest-proxy.company.com:3128:none"
)

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

# Setup directories
setup_directories() {
    for dir in "$CONFIG_DIR" "$PROFILES_DIR" "$POLICIES_DIR" "$BACKUP_DIR"; do
        if [[ ! -d "$dir" ]]; then
            mkdir -p "$dir"
            log_action "Created directory: $dir"
        fi
    done
}

# Backup current network configuration
backup_network_config() {
    local backup_timestamp
    backup_timestamp=$(date '+%Y%m%d_%H%M%S')
    local backup_file="$BACKUP_DIR/network_config_$backup_timestamp.tar.gz"
    
    log_action "Creating network configuration backup: $backup_file"
    
    # Create temporary backup directory
    local temp_backup="/tmp/network_backup_$$"
    mkdir -p "$temp_backup"
    
    # Export current settings
    {
        echo "# Wi-Fi Service Status"
        networksetup -getnetworkserviceenabled Wi-Fi
        
        echo -e "\n# Wi-Fi Power Status"
        networksetup -getairportpower en0
        
        echo -e "\n# Current Network"
        networksetup -getairportnetwork en0
        
        echo -e "\n# Network Info"
        networksetup -getinfo Wi-Fi
        
        echo -e "\n# DNS Servers"
        networksetup -getdnsservers Wi-Fi
        
        echo -e "\n# Search Domains"
        networksetup -getsearchdomains Wi-Fi
        
        echo -e "\n# Web Proxy"
        networksetup -getwebproxy Wi-Fi
        
        echo -e "\n# Secure Web Proxy"
        networksetup -getsecurewebproxy Wi-Fi
        
        echo -e "\n# Auto Proxy"
        networksetup -getautoproxyurl Wi-Fi
        
        echo -e "\n# Proxy Bypass Domains"
        networksetup -getproxybypassdomains Wi-Fi
        
    } > "$temp_backup/current_config.txt"
    
    # Create compressed backup
    if tar -czf "$backup_file" -C "$(dirname "$temp_backup")" "$(basename "$temp_backup")" 2>/dev/null; then
        log_action "✅ Network backup created: $backup_file"
        rm -rf "$temp_backup"
        echo "$backup_file"
        return 0
    else
        log_action "❌ Network backup failed"
        rm -rf "$temp_backup"
        return 1
    fi
}

# Configure DNS servers
configure_dns() {
    local dns_profile="$1"
    local custom_dns="$2"
    
    log_action "Configuring DNS servers: $dns_profile"
    
    local dns_servers
    if [[ -n "$custom_dns" ]]; then
        dns_servers="$custom_dns"
    else
        dns_servers="${DNS_CONFIGS[$dns_profile]}"
    fi
    
    if [[ -z "$dns_servers" ]]; then
        log_action "❌ Unknown DNS profile or empty configuration: $dns_profile"
        return 1
    fi
    
    # Set DNS servers
    if networksetup -setdnsservers Wi-Fi $dns_servers; then
        log_action "✅ DNS servers configured: $dns_servers"
        
        # Verify configuration
        local current_dns
        current_dns=$(networksetup -getdnsservers Wi-Fi)
        log_action "Current DNS servers: $current_dns"
        
        return 0
    else
        log_action "❌ Failed to configure DNS servers"
        return 1
    fi
}

# Configure search domains
configure_search_domains() {
    local domains="$*"
    
    if [[ -z "$domains" ]]; then
        log_action "Clearing search domains"
        networksetup -setsearchdomains Wi-Fi "Empty"
    else
        log_action "Setting search domains: $domains"
        networksetup -setsearchdomains Wi-Fi $domains
    fi
    
    if [[ $? -eq 0 ]]; then
        log_action "✅ Search domains configured successfully"
        return 0
    else
        log_action "❌ Failed to configure search domains"
        return 1
    fi
}

# Configure web proxy
configure_web_proxy() {
    local proxy_type="$1"
    local proxy_config="$2"
    
    log_action "Configuring web proxy: $proxy_type"
    
    case "$proxy_type" in
        "none")
            # Disable all proxies
            networksetup -setwebproxystate Wi-Fi off
            networksetup -setsecurewebproxystate Wi-Fi off
            networksetup -setautoproxystate Wi-Fi off
            log_action "✅ All proxies disabled"
            ;;
        "web")
            local proxy_server proxy_port auth_required username password
            IFS=':' read -ra PROXY_PARTS <<< "$proxy_config"
            proxy_server="${PROXY_PARTS[0]}"
            proxy_port="${PROXY_PARTS[1]}"
            auth_required="${PROXY_PARTS[2]}"
            username="${PROXY_PARTS[3]:-}"
            password="${PROXY_PARTS[4]:-}"
            
            if [[ "$auth_required" == "authenticated" && -n "$username" && -n "$password" ]]; then
                networksetup -setwebproxy Wi-Fi "$proxy_server" "$proxy_port" on "$username" "$password"
            else
                networksetup -setwebproxy Wi-Fi "$proxy_server" "$proxy_port" off
            fi
            
            networksetup -setwebproxystate Wi-Fi on
            log_action "✅ Web proxy configured: $proxy_server:$proxy_port"
            ;;
        "auto")
            networksetup -setautoproxyurl Wi-Fi "$proxy_config"
            networksetup -setautoproxystate Wi-Fi on
            log_action "✅ Automatic proxy configured: $proxy_config"
            ;;
        *)
            log_action "❌ Unknown proxy type: $proxy_type"
            return 1
            ;;
    esac
    
    return 0
}

# Configure proxy bypass domains
configure_proxy_bypass() {
    local domains="$*"
    
    log_action "Configuring proxy bypass domains: $domains"
    
    if [[ -n "$domains" ]]; then
        networksetup -setproxybypassdomains Wi-Fi $domains
    else
        networksetup -setproxybypassdomains Wi-Fi "Empty"
    fi
    
    if [[ $? -eq 0 ]]; then
        log_action "✅ Proxy bypass domains configured"
        return 0
    else
        log_action "❌ Failed to configure proxy bypass domains"
        return 1
    fi
}

# Deploy network profile
deploy_network_profile() {
    local profile_name="$1"
    local custom_settings="$2"
    
    log_action "Deploying network profile: $profile_name"
    
    # Get profile configuration
    local profile_config="${NETWORK_PROFILES[$profile_name]}"
    if [[ -z "$profile_config" ]]; then
        log_action "❌ Unknown network profile: $profile_name"
        return 1
    fi
    
    # Backup current configuration
    local backup_file
    backup_file=$(backup_network_config)
    
    # Parse profile settings
    local dns_setting proxy_setting security_setting
    IFS=',' read -ra SETTINGS <<< "$profile_config"
    
    for setting in "${SETTINGS[@]}"; do
        IFS='=' read -ra SETTING_PAIR <<< "$setting"
        local key="${SETTING_PAIR[0]}"
        local value="${SETTING_PAIR[1]}"
        
        case "$key" in
            "dns")
                configure_dns "$value"
                ;;
            "proxy")
                case "$value" in
                    "auto")
                        configure_web_proxy "auto" "${PROXY_CONFIGS[corporate_auto]}"
                        ;;
                    "mandatory")
                        configure_web_proxy "web" "${PROXY_CONFIGS[corporate_web]}"
                        ;;
                    "none")
                        configure_web_proxy "none"
                        ;;
                    "bypass")
                        configure_web_proxy "none"
                        configure_proxy_bypass "*.local *.company.com localhost"
                        ;;
                esac
                ;;
            "security")
                log_action "Security setting: $value (requires manual Wi-Fi connection)"
                ;;
        esac
    done
    
    # Apply custom settings if provided
    if [[ -n "$custom_settings" ]]; then
        log_action "Applying custom settings: $custom_settings"
        # Parse and apply custom settings here
    fi
    
    # Generate deployment report
    generate_profile_report "$profile_name" "$backup_file"
    
    log_action "✅ Network profile deployed: $profile_name"
    return 0
}

# Generate profile deployment report
generate_profile_report() {
    local profile_name="$1"
    local backup_file="$2"
    local report_file="$CONFIG_DIR/profile_report_$(date '+%Y%m%d_%H%M%S').json"
    
    log_action "Generating profile deployment report: $report_file"
    
    cat > "$report_file" << EOF
{
    "deployment_metadata": {
        "timestamp": "$(date -Iseconds)",
        "profile_name": "$profile_name",
        "hostname": "$(hostname)",
        "backup_file": "$backup_file",
        "generator": "MacFleet Wi-Fi Manager"
    },
    "network_configuration": {
        "wifi_service_enabled": "$(networksetup -getnetworkserviceenabled Wi-Fi)",
        "wifi_power_status": "$(networksetup -getairportpower en0)",
        "current_network": "$(networksetup -getairportnetwork en0)",
        "dns_servers": "$(networksetup -getdnsservers Wi-Fi | tr '\n' ' ')",
        "search_domains": "$(networksetup -getsearchdomains Wi-Fi | tr '\n' ' ')",
        "web_proxy_state": "$(networksetup -getwebproxystate Wi-Fi)",
        "auto_proxy_state": "$(networksetup -getautoproxystate Wi-Fi)"
    },
    "system_info": {
        "os_version": "$(sw_vers -productVersion)",
        "build_version": "$(sw_vers -buildVersion)",
        "serial_number": "$(system_profiler SPHardwareDataType | grep 'Serial Number' | awk '{print $4}')",
        "wifi_hardware": "$(system_profiler SPAirPortDataType | grep 'Card Type' | awk -F': ' '{print $2}')"
    }
}
EOF

    log_action "✅ Profile deployment report generated: $report_file"
    echo "$report_file"
}

# Monitor network connectivity
monitor_connectivity() {
    local test_hosts=("8.8.8.8" "apple.com" "github.com")
    local connectivity_report="$CONFIG_DIR/connectivity_$(date '+%Y%m%d_%H%M%S').json"
    
    log_action "Starting connectivity monitoring"
    
    cat > "$connectivity_report" << EOF
{
    "monitoring_timestamp": "$(date -Iseconds)",
    "hostname": "$(hostname)",
    "connectivity_tests": [
EOF

    local first=true
    for host in "${test_hosts[@]}"; do
        if [[ "$first" == true ]]; then
            first=false
        else
            echo "," >> "$connectivity_report"
        fi
        
        local start_time end_time duration result
        start_time=$(date +%s.%N)
        
        if ping -c 3 -W 5000 "$host" >/dev/null 2>&1; then
            result="success"
        else
            result="failed"
        fi
        
        end_time=$(date +%s.%N)
        duration=$(awk "BEGIN {printf \"%.3f\", $end_time - $start_time}")
        
        cat >> "$connectivity_report" << EOF
        {
            "host": "$host",
            "result": "$result",
            "duration_seconds": $duration,
            "timestamp": "$(date -Iseconds)"
        }
EOF
        
        log_action "Connectivity test: $host - $result ($duration seconds)"
    done
    
    cat >> "$connectivity_report" << EOF
    ],
    "network_status": {
        "current_ssid": "$(networksetup -getairportnetwork en0 | cut -d' ' -f4- || echo 'Not connected')",
        "signal_strength": "$(airport -I | grep ' RSSI:' | awk '{print $2}' || echo 'N/A')",
        "ip_address": "$(ifconfig en0 | grep 'inet ' | awk '{print $2}' || echo 'N/A')"
    }
}
EOF

    log_action "✅ Connectivity monitoring completed: $connectivity_report"
    echo "$connectivity_report"
}

# Wi-Fi security scan
security_scan() {
    local scan_report="$CONFIG_DIR/security_scan_$(date '+%Y%m%d_%H%M%S').json"
    
    log_action "Starting Wi-Fi security scan"
    
    # Scan for available networks
    local available_networks
    available_networks=$(/System/Library/PrivateFrameworks/Apple80211.framework/Versions/Current/Resources/airport -s)
    
    cat > "$scan_report" << EOF
{
    "scan_timestamp": "$(date -Iseconds)",
    "hostname": "$(hostname)",
    "security_analysis": {
        "open_networks": [],
        "wep_networks": [],
        "wpa_networks": [],
        "enterprise_networks": []
    },
    "network_details": [
EOF

    # Parse networks and categorize by security
    echo "$available_networks" | tail -n +2 | while IFS= read -r line; do
        local ssid security
        ssid=$(echo "$line" | awk '{print $1}')
        security=$(echo "$line" | awk '{for(i=7;i<=NF;i++) printf "%s ", $i; print ""}' | sed 's/[[:space:]]*$//')
        
        if [[ -n "$ssid" && "$ssid" != "SSID" ]]; then
            echo "Found network: $ssid - Security: $security" >&2
        fi
    done
    
    cat >> "$scan_report" << EOF
    ]
}
EOF

    log_action "✅ Wi-Fi security scan completed: $scan_report"
    echo "$scan_report"
}

# Reset network configuration
reset_network_config() {
    local reset_type="${1:-partial}"
    
    log_action "Resetting network configuration: $reset_type"
    
    # Backup before reset
    backup_network_config
    
    case "$reset_type" in
        "dns")
            log_action "Resetting DNS configuration"
            networksetup -setdnsservers Wi-Fi "Empty"
            networksetup -setsearchdomains Wi-Fi "Empty"
            ;;
        "proxy")
            log_action "Resetting proxy configuration"
            networksetup -setwebproxystate Wi-Fi off
            networksetup -setsecurewebproxystate Wi-Fi off
            networksetup -setautoproxystate Wi-Fi off
            networksetup -setproxybypassdomains Wi-Fi "Empty"
            ;;
        "full")
            log_action "Performing full network reset"
            # Reset all network settings
            networksetup -setdnsservers Wi-Fi "Empty"
            networksetup -setsearchdomains Wi-Fi "Empty"
            networksetup -setwebproxystate Wi-Fi off
            networksetup -setsecurewebproxystate Wi-Fi off
            networksetup -setautoproxystate Wi-Fi off
            networksetup -setproxybypassdomains Wi-Fi "Empty"
            
            # Reset Wi-Fi interface
            networksetup -setairportpower en0 off
            sleep 2
            networksetup -setairportpower en0 on
            ;;
        *)
            log_action "Resetting DNS and proxy settings"
            networksetup -setdnsservers Wi-Fi "Empty"
            networksetup -setwebproxystate Wi-Fi off
            ;;
    esac
    
    log_action "✅ Network configuration reset completed"
    return 0
}

# Main execution function
main() {
    local action="${1:-status}"
    local profile_name="$2"
    local additional_param="$3"
    
    log_action "=== MacFleet Wi-Fi Management Started ==="
    log_action "Action: $action"
    log_action "Profile: ${profile_name:-N/A}"
    
    # Setup
    setup_directories
    
    case "$action" in
        "deploy")
            if [[ -z "$profile_name" ]]; then
                echo "Available network profiles:"
                for profile in "${!NETWORK_PROFILES[@]}"; do
                    echo "  - $profile: ${NETWORK_PROFILES[$profile]}"
                done
                echo ""
                echo "Usage: $0 deploy <profile_name> [custom_settings]"
                exit 1
            fi
            deploy_network_profile "$profile_name" "$additional_param"
            ;;
        "status")
            network_diagnostics
            ;;
        "scan")
            security_scan
            ;;
        "monitor")
            monitor_connectivity
            ;;
        "dns")
            if [[ -z "$profile_name" ]]; then
                echo "Available DNS profiles: ${!DNS_CONFIGS[*]}"
                echo "Usage: $0 dns <profile_name|custom_servers>"
                exit 1
            fi
            configure_dns "$profile_name" "$additional_param"
            ;;
        "proxy")
            if [[ -z "$profile_name" ]]; then
                echo "Usage: $0 proxy <none|web|auto> [config]"
                exit 1
            fi
            configure_web_proxy "$profile_name" "$additional_param"
            ;;
        "reset")
            reset_network_config "$profile_name"
            ;;
        "backup")
            backup_network_config
            ;;
        *)
            echo "Usage: $0 {deploy|status|scan|monitor|dns|proxy|reset|backup}"
            echo "  deploy  - Deploy network profile"
            echo "  status  - Show network status and diagnostics"
            echo "  scan    - Perform Wi-Fi security scan"
            echo "  monitor - Monitor network connectivity"
            echo "  dns     - Configure DNS servers"
            echo "  proxy   - Configure proxy settings"
            echo "  reset   - Reset network configuration"
            echo "  backup  - Backup current network configuration"
            exit 1
            ;;
    esac
    
    log_action "=== Wi-Fi management completed ==="
}

# Execute main function
main "$@"

Advanced Network Configuration

Enterprise Wi-Fi Profile Management

#!/bin/bash

# Create custom network profile
create_network_profile() {
    local profile_name="$1"
    local ssid="$2"
    local security_type="$3"
    local proxy_config="$4"
    local dns_config="$5"
    
    local profile_file="$PROFILES_DIR/${profile_name}.json"
    
    cat > "$profile_file" << EOF
{
    "profile_name": "$profile_name",
    "created_date": "$(date -Iseconds)",
    "wifi_settings": {
        "ssid": "$ssid",
        "security_type": "$security_type",
        "auto_connect": true,
        "priority": 100
    },
    "proxy_settings": {
        "type": "$proxy_config",
        "auto_config_url": "",
        "manual_config": {
            "server": "",
            "port": "",
            "requires_auth": false
        },
        "bypass_domains": ["*.local", "localhost"]
    },
    "dns_settings": {
        "servers": "$dns_config",
        "search_domains": ["company.com", "local"]
    },
    "security_policies": {
        "require_certificate": false,
        "allow_untrusted": false,
        "minimum_security": "WPA2"
    }
}
EOF

    echo "Network profile created: $profile_file"
}

Automated Network Switching

#!/bin/bash

# Smart network switching based on location/SSID priority
smart_network_switching() {
    local priority_networks=("Corporate-WiFi" "Corporate-Guest" "Office-5G")
    local current_network
    current_network=$(networksetup -getairportnetwork en0 | cut -d' ' -f4-)
    
    echo "Current network: $current_network"
    echo "Scanning for priority networks..."
    
    # Get available networks
    local available_networks
    available_networks=$(/System/Library/PrivateFrameworks/Apple80211.framework/Versions/Current/Resources/airport -s | tail -n +2 | awk '{print $1}')
    
    # Check for priority networks
    for priority_ssid in "${priority_networks[@]}"; do
        if echo "$available_networks" | grep -q "$priority_ssid"; then
            if [[ "$current_network" != "$priority_ssid" ]]; then
                echo "Found higher priority network: $priority_ssid"
                echo "Would switch from: $current_network"
                # Note: Actual connection requires credentials
                return 0
            fi
        fi
    done
    
    echo "Already connected to optimal network"
}

Network Quality Monitoring

#!/bin/bash

# Monitor network quality and performance
monitor_network_quality() {
    local duration="${1:-60}"  # monitoring duration in seconds
    local interval="${2:-5}"   # check interval in seconds
    
    echo "=== Network Quality Monitoring ==="
    echo "Duration: ${duration}s, Interval: ${interval}s"
    
    local start_time end_time
    start_time=$(date +%s)
    end_time=$((start_time + duration))
    
    while [[ $(date +%s) -lt $end_time ]]; do
        local timestamp signal_strength link_quality tx_rate
        timestamp=$(date '+%H:%M:%S')
        
        # Get Wi-Fi metrics
        local airport_info
        airport_info=$(/System/Library/PrivateFrameworks/Apple80211.framework/Versions/Current/Resources/airport -I)
        
        signal_strength=$(echo "$airport_info" | grep 'RSSI:' | awk '{print $2}')
        link_quality=$(echo "$airport_info" | grep 'link auth:' | awk '{print $3}')
        tx_rate=$(echo "$airport_info" | grep 'lastTxRate:' | awk '{print $2}')
        
        # Test connectivity speed
        local ping_time
        ping_time=$(ping -c 1 8.8.8.8 2>/dev/null | grep 'time=' | awk -F'time=' '{print $2}' | awk '{print $1}')
        
        printf "%s | Signal: %sdBm | Quality: %s | Speed: %sMbps | Ping: %s\n" \
               "$timestamp" "$signal_strength" "$link_quality" "$tx_rate" "${ping_time:-timeout}"
        
        sleep "$interval"
    done
}

Security and Compliance

Network Security Audit

#!/bin/bash

# Comprehensive network security audit
network_security_audit() {
    local audit_report="$CONFIG_DIR/security_audit_$(date '+%Y%m%d_%H%M%S').json"
    
    echo "=== Network Security Audit ==="
    log_action "Starting network security audit"
    
    cat > "$audit_report" << EOF
{
    "audit_timestamp": "$(date -Iseconds)",
    "hostname": "$(hostname)",
    "security_assessment": {
        "wifi_encryption": "$(networksetup -getairportnetwork en0 | grep -o 'WPA\\|WEP\\|None' || echo 'Unknown')",
        "proxy_enabled": "$(networksetup -getwebproxystate Wi-Fi)",
        "dns_servers": "$(networksetup -getdnsservers Wi-Fi | tr '\n' ',' | sed 's/,$//')",
        "firewall_status": "$(defaults read /Library/Preferences/com.apple.alf globalstate 2>/dev/null || echo 'Unknown')"
    },
    "vulnerability_checks": [
EOF

    # Check for open networks in range
    local open_networks
    open_networks=$(/System/Library/PrivateFrameworks/Apple80211.framework/Versions/Current/Resources/airport -s | grep -E 'NONE|--' | wc -l)
    
    # Check for weak DNS
    local dns_servers
    dns_servers=$(networksetup -getdnsservers Wi-Fi)
    
    # Generate security recommendations
    local recommendations=()
    
    if [[ "$open_networks" -gt 0 ]]; then
        recommendations+=("Avoid connecting to $open_networks open networks detected")
    fi
    
    if echo "$dns_servers" | grep -q "There aren't any DNS Servers"; then
        recommendations+=("Configure secure DNS servers")
    fi
    
    cat >> "$audit_report" << EOF
    ],
    "recommendations": [
EOF

    local first=true
    for rec in "${recommendations[@]}"; do
        if [[ "$first" == true ]]; then
            first=false
        else
            echo "," >> "$audit_report"
        fi
        echo "        \"$rec\"" >> "$audit_report"
    done
    
    cat >> "$audit_report" << EOF
    ]
}
EOF

    log_action "✅ Security audit completed: $audit_report"
    echo "$audit_report"
}

Compliance Policy Enforcement

#!/bin/bash

# Enforce enterprise compliance policies
enforce_compliance_policy() {
    local policy_name="$1"
    
    log_action "Enforcing compliance policy: $policy_name"
    
    case "$policy_name" in
        "corporate")
            # Corporate policy: Secure DNS, mandatory proxy, no open networks
            configure_dns "corporate"
            configure_web_proxy "web" "${PROXY_CONFIGS[corporate_web]}"
            configure_proxy_bypass "*.company.com localhost"
            ;;
        "education")
            # Education policy: Safe DNS, content filtering proxy
            configure_dns "public"
            configure_web_proxy "auto" "http://filter.school.edu/proxy.pac"
            ;;
        "healthcare")
            # Healthcare policy: HIPAA-compliant settings
            configure_dns "secure"
            configure_web_proxy "web" "secure-proxy.hospital.org:8080:authenticated"
            ;;
        "government")
            # Government policy: Maximum security
            configure_dns "secure"
            configure_web_proxy "web" "gov-proxy.agency.gov:3128:authenticated"
            configure_proxy_bypass ""  # No bypass domains
            ;;
        *)
            log_action "❌ Unknown compliance policy: $policy_name"
            return 1
            ;;
    esac
    
    log_action "✅ Compliance policy enforced: $policy_name"
    return 0
}

Network Troubleshooting

Automated Network Repair

#!/bin/bash

# Automated network troubleshooting and repair
network_repair() {
    local repair_level="${1:-basic}"
    
    log_action "Starting network repair: $repair_level"
    
    echo "=== MacFleet Network Repair ==="
    
    # Basic connectivity test
    echo "🔍 Testing basic connectivity..."
    if ping -c 3 8.8.8.8 >/dev/null 2>&1; then
        echo "✅ Internet connectivity: OK"
    else
        echo "❌ Internet connectivity: FAILED"
        
        case "$repair_level" in
            "basic")
                echo "🔧 Attempting basic repair..."
                # Cycle Wi-Fi
                networksetup -setairportpower en0 off
                sleep 3
                networksetup -setairportpower en0 on
                sleep 5
                ;;
            "advanced")
                echo "🔧 Attempting advanced repair..."
                # Full network reset
                reset_network_config "full"
                sleep 10
                ;;
            "complete")
                echo "🔧 Attempting complete repair..."
                # Reset network preferences
                sudo rm -f /Library/Preferences/SystemConfiguration/com.apple.airport.preferences.plist
                sudo rm -f /Library/Preferences/SystemConfiguration/NetworkInterfaces.plist
                echo "⚠️  System restart required for complete repair"
                ;;
        esac
        
        # Retest after repair
        echo "🔄 Retesting connectivity..."
        if ping -c 3 8.8.8.8 >/dev/null 2>&1; then
            echo "✅ Repair successful"
            log_action "Network repair successful: $repair_level"
        else
            echo "❌ Repair failed - escalate to manual intervention"
            log_action "Network repair failed: $repair_level"
        fi
    fi
}

Network Performance Optimization

#!/bin/bash

# Optimize network performance settings
optimize_network_performance() {
    echo "=== Network Performance Optimization ==="
    
    # Check current MTU
    local current_mtu
    current_mtu=$(networksetup -getMTU Wi-Fi | awk '{print $NF}')
    echo "Current MTU: $current_mtu"
    
    # Optimize for different scenarios
    local optimization_type="${1:-balanced}"
    
    case "$optimization_type" in
        "throughput")
            echo "🚀 Optimizing for maximum throughput..."
            networksetup -setMTU Wi-Fi 1500
            ;;
        "latency")
            echo "⚡ Optimizing for low latency..."
            networksetup -setMTU Wi-Fi 1200
            ;;
        "balanced")
            echo "⚖️  Applying balanced optimization..."
            networksetup -setMTU Wi-Fi 1400
            ;;
        *)
            echo "❌ Unknown optimization type: $optimization_type"
            return 1
            ;;
    esac
    
    # Clear DNS cache
    echo "🧹 Clearing DNS cache..."
    sudo dscacheutil -flushcache
    sudo killall -HUP mDNSResponder
    
    echo "✅ Network optimization completed"
}

Best Practices

🚀 Performance Optimization

  • Monitor network quality regularly and switch to optimal networks
  • Configure appropriate MTU sizes for your network environment
  • Use local DNS caching to improve resolution speeds
  • Optimize proxy settings for your specific use case

🔐 Security Guidelines

  • Always use encrypted networks (WPA2/WPA3) in enterprise environments
  • Configure secure DNS servers to prevent DNS poisoning
  • Implement proxy policies for content filtering and security
  • Regular security audits to identify network vulnerabilities

📋 Management Best Practices

  • Profile-based configuration for different user groups and locations
  • Centralized policy enforcement across all fleet devices
  • Regular backup of network configurations before changes
  • Automated monitoring and alerting for connectivity issues

🔍 Troubleshooting Tips

  • Use network diagnostics to identify configuration issues
  • Monitor signal strength and network quality metrics
  • Test connectivity to multiple endpoints for comprehensive validation
  • Document network changes for audit trails and troubleshooting

Important Notes

  • Network changes take effect immediately but may require reconnection
  • Proxy authentication credentials should be managed securely
  • DNS changes may require cache flushing to take effect
  • Some enterprise networks require specific certificates for authentication
  • Always backup configurations before making significant changes

Wi-Fi Control on macOS

Control and manage Wi-Fi settings across your MacFleet devices using advanced command-line tools and centralized wireless policies. This tutorial covers Wi-Fi power management, connection control, security enforcement, and enterprise-grade wireless network management with comprehensive monitoring and compliance capabilities.

Understanding macOS Wi-Fi Management

macOS provides several command-line tools for Wi-Fi management:

  • networksetup - Primary tool for network configuration and control
  • airport - Low-level wireless interface management utility
  • ifconfig - Network interface configuration tool
  • System Preferences - GUI equivalent for wireless settings

Enterprise Wi-Fi control requires careful consideration of security policies, power management, and compliance requirements.

Basic Wi-Fi Control Commands

Turn Off Wi-Fi

#!/bin/bash

# Basic Wi-Fi disable command
turn_off_wifi_basic() {
    # Get the airport interface name
    local AIRPORT=$(networksetup -listallhardwareports | grep -A 1 Wi-Fi | grep Device | awk '{print $2}')
    
    if [[ -n "$AIRPORT" ]]; then
        networksetup -setairportpower "$AIRPORT" off
        
        if [[ $? -eq 0 ]]; then
            echo "✅ Wi-Fi turned off successfully"
            return 0
        else
            echo "❌ Failed to turn off Wi-Fi"
            return 1
        fi
    else
        echo "❌ Wi-Fi interface not found"
        return 1
    fi
}

# Example usage
turn_off_wifi_basic

Turn On Wi-Fi

#!/bin/bash

# Turn on Wi-Fi with verification
turn_on_wifi() {
    local interface_name="$1"
    
    # Auto-detect interface if not provided
    if [[ -z "$interface_name" ]]; then
        interface_name=$(networksetup -listallhardwareports | grep -A 1 Wi-Fi | grep Device | awk '{print $2}')
    fi
    
    if [[ -z "$interface_name" ]]; then
        echo "❌ Wi-Fi interface not found"
        return 1
    fi
    
    echo "Turning on Wi-Fi interface: $interface_name"
    networksetup -setairportpower "$interface_name" on
    
    # Wait for interface to come up
    sleep 3
    
    # Verify Wi-Fi is enabled
    local wifi_status
    wifi_status=$(networksetup -getairportpower "$interface_name" | grep "On")
    
    if [[ -n "$wifi_status" ]]; then
        echo "✅ Wi-Fi turned on successfully"
        return 0
    else
        echo "❌ Failed to turn on Wi-Fi"
        return 1
    fi
}

# Example usage
# turn_on_wifi "en0"

Check Wi-Fi Status

#!/bin/bash

# Check current Wi-Fi status with detailed information
check_wifi_status() {
    echo "=== Wi-Fi Status Report ==="
    echo "Generated: $(date)"
    echo "=========================="
    echo ""
    
    # Get all Wi-Fi interfaces
    local wifi_interfaces
    wifi_interfaces=$(networksetup -listallhardwareports | grep -A 1 Wi-Fi | grep Device | awk '{print $2}')
    
    if [[ -z "$wifi_interfaces" ]]; then
        echo "❌ No Wi-Fi interfaces found"
        return 1
    fi
    
    for interface in $wifi_interfaces; do
        echo "Interface: $interface"
        echo "-----------------"
        
        # Power status
        local power_status
        power_status=$(networksetup -getairportpower "$interface")
        echo "Power Status: $power_status"
        
        # Connection status
        if echo "$power_status" | grep -q "On"; then
            # Get current network
            local current_network
            current_network=$(networksetup -getairportnetwork "$interface" | cut -d' ' -f4-)
            echo "Current Network: $current_network"
            
            # Get IP address if connected
            local ip_address
            ip_address=$(ifconfig "$interface" | grep "inet " | awk '{print $2}')
            if [[ -n "$ip_address" ]]; then
                echo "IP Address: $ip_address"
            else
                echo "IP Address: Not assigned"
            fi
            
            # Signal strength (if available)
            if command -v airport >/dev/null 2>&1; then
                local signal_info
                signal_info=$(airport -I | grep "agrCtlRSSI" | awk '{print $2}')
                if [[ -n "$signal_info" ]]; then
                    echo "Signal Strength: $signal_info dBm"
                fi
            fi
        else
            echo "Wi-Fi is disabled"
        fi
        
        echo ""
    done
}

# Execute status check
check_wifi_status

Advanced Wi-Fi Management

Wi-Fi Interface Discovery

#!/bin/bash

# Discover and analyze Wi-Fi interfaces
discover_wifi_interfaces() {
    echo "=== Wi-Fi Interface Discovery ==="
    echo ""
    
    # List all network hardware
    echo "1. ALL NETWORK HARDWARE:"
    echo "------------------------"
    networksetup -listallhardwareports
    echo ""
    
    # Focus on Wi-Fi interfaces
    echo "2. WI-FI INTERFACES DETECTED:"
    echo "----------------------------"
    local wifi_count=0
    
    while IFS= read -r line; do
        if echo "$line" | grep -q "Wi-Fi"; then
            echo "Hardware Port: $line"
            # Get the next line which contains device name
            read -r device_line
            echo "Device: $device_line"
            
            # Extract device name
            local device_name
            device_name=$(echo "$device_line" | awk '{print $2}')
            
            # Get MAC address
            local mac_address
            mac_address=$(ifconfig "$device_name" 2>/dev/null | grep "ether" | awk '{print $2}')
            if [[ -n "$mac_address" ]]; then
                echo "MAC Address: $mac_address"
            fi
            
            # Get current status
            local power_status
            power_status=$(networksetup -getairportpower "$device_name" 2>/dev/null)
            echo "Power Status: $power_status"
            
            echo ""
            ((wifi_count++))
        fi
    done < <(networksetup -listallhardwareports)
    
    echo "Total Wi-Fi interfaces found: $wifi_count"
    
    if [[ $wifi_count -eq 0 ]]; then
        echo "⚠️  No Wi-Fi interfaces detected"
        return 1
    fi
    
    return 0
}

# Execute interface discovery
discover_wifi_interfaces

Network Scanning and Analysis

#!/bin/bash

# Scan for available Wi-Fi networks
scan_wifi_networks() {
    local interface_name="$1"
    local scan_type="${2:-basic}"  # basic, detailed, security
    
    # Auto-detect interface if not provided
    if [[ -z "$interface_name" ]]; then
        interface_name=$(networksetup -listallhardwareports | grep -A 1 Wi-Fi | grep Device | awk '{print $2}')
    fi
    
    if [[ -z "$interface_name" ]]; then
        echo "❌ Wi-Fi interface not found"
        return 1
    fi
    
    echo "=== Wi-Fi Network Scan ==="
    echo "Interface: $interface_name"
    echo "Scan Type: $scan_type"
    echo "========================="
    echo ""
    
    # Ensure Wi-Fi is on for scanning
    local power_status
    power_status=$(networksetup -getairportpower "$interface_name")
    
    if echo "$power_status" | grep -q "Off"; then
        echo "Enabling Wi-Fi for scanning..."
        networksetup -setairportpower "$interface_name" on
        sleep 3
    fi
    
    case "$scan_type" in
        "basic")
            # Basic network list
            echo "Available Networks:"
            echo "-------------------"
            if command -v airport >/dev/null 2>&1; then
                airport -s
            else
                echo "airport command not available, using networksetup scan"
                # Note: networksetup doesn't have direct scan command, using airport utility
            fi
            ;;
        "detailed")
            # Detailed network information
            echo "Detailed Network Analysis:"
            echo "-------------------------"
            if command -v airport >/dev/null 2>&1; then
                airport -s | while IFS= read -r line; do
                    if [[ -n "$line" && ! "$line" =~ ^[[:space:]]*$ ]]; then
                        echo "Network: $line"
                        # Extract SSID and signal strength
                        local ssid signal
                        ssid=$(echo "$line" | awk '{print $1}')
                        signal=$(echo "$line" | awk '{print $3}')
                        
                        if [[ -n "$signal" ]]; then
                            if [[ "$signal" -gt -50 ]]; then
                                echo "  Signal Quality: Excellent ($signal dBm)"
                            elif [[ "$signal" -gt -70 ]]; then
                                echo "  Signal Quality: Good ($signal dBm)"
                            elif [[ "$signal" -gt -80 ]]; then
                                echo "  Signal Quality: Fair ($signal dBm)"
                            else
                                echo "  Signal Quality: Poor ($signal dBm)"
                            fi
                        fi
                        echo ""
                    fi
                done
            fi
            ;;
        "security")
            # Security analysis of networks
            echo "Security Analysis:"
            echo "-----------------"
            if command -v airport >/dev/null 2>&1; then
                airport -s | grep -E "(WPA|WEP|NONE)" | while IFS= read -r line; do
                    local ssid security
                    ssid=$(echo "$line" | awk '{print $1}')
                    security=$(echo "$line" | grep -o -E "(WPA2|WPA3|WPA|WEP|NONE)")
                    
                    case "$security" in
                        "WPA3")
                            echo "✅ $ssid: Secure (WPA3)"
                            ;;
                        "WPA2")
                            echo "✅ $ssid: Secure (WPA2)"
                            ;;
                        "WPA")
                            echo "⚠️  $ssid: Moderately Secure (WPA)"
                            ;;
                        "WEP")
                            echo "❌ $ssid: Insecure (WEP - Deprecated)"
                            ;;
                        "NONE"|*)
                            echo "❌ $ssid: Open Network (No Security)"
                            ;;
                    esac
                done
            fi
            ;;
    esac
}

# Example usage
# scan_wifi_networks "en0" "detailed"

Enterprise Wi-Fi Control System

#!/bin/bash

# MacFleet Enterprise Wi-Fi Control System
# Comprehensive wireless management, security enforcement, and compliance monitoring

# Configuration
LOG_FILE="/var/log/macfleet_wifi_control.log"
CONFIG_FILE="/etc/macfleet/wifi_config.conf"
BACKUP_DIR="/var/backups/macfleet/wifi"
POLICY_DIR="/etc/macfleet/wifi_policies"

# Create directory structure
setup_directories() {
    mkdir -p "$(dirname "$LOG_FILE")" "$BACKUP_DIR" "$POLICY_DIR" "$(dirname "$CONFIG_FILE")"
    touch "$LOG_FILE"
    
    # Set appropriate permissions
    chmod 755 "$BACKUP_DIR" "$POLICY_DIR"
}

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

# Enterprise Wi-Fi policy enforcement
enforce_wifi_policy() {
    local policy_name="$1"
    local policy_file="$POLICY_DIR/${policy_name}.policy"
    
    if [[ ! -f "$policy_file" ]]; then
        log_action "ERROR: Wi-Fi policy not found: $policy_name"
        return 1
    fi
    
    log_action "Enforcing Wi-Fi policy: $policy_name"
    
    # Load policy configuration
    source "$policy_file"
    
    # Get Wi-Fi interface
    local wifi_interface
    wifi_interface=$(networksetup -listallhardwareports | grep -A 1 Wi-Fi | grep Device | awk '{print $2}')
    
    if [[ -z "$wifi_interface" ]]; then
        log_action "ERROR: No Wi-Fi interface found"
        return 1
    fi
    
    # Apply policy settings
    case "${WIFI_POLICY_ACTION:-disable}" in
        "disable")
            networksetup -setairportpower "$wifi_interface" off
            log_action "Wi-Fi disabled per policy: $policy_name"
            ;;
        "enable")
            networksetup -setairportpower "$wifi_interface" on
            log_action "Wi-Fi enabled per policy: $policy_name"
            ;;
        "scheduled")
            apply_scheduled_wifi_policy "$wifi_interface" "$policy_name"
            ;;
        "conditional")
            apply_conditional_wifi_policy "$wifi_interface" "$policy_name"
            ;;
        *)
            log_action "ERROR: Unknown policy action: ${WIFI_POLICY_ACTION}"
            return 1
            ;;
    esac
    
    return 0
}

# Scheduled Wi-Fi control
apply_scheduled_wifi_policy() {
    local interface="$1"
    local policy_name="$2"
    local current_hour=$(date +%H)
    local current_day=$(date +%u)  # 1=Monday, 7=Sunday
    
    log_action "Applying scheduled Wi-Fi policy: $policy_name"
    
    # Load schedule from policy
    local enable_hours="${WIFI_ENABLE_HOURS:-09-17}"
    local enable_days="${WIFI_ENABLE_DAYS:-1-5}"
    
    # Parse time range
    local start_hour end_hour
    start_hour=$(echo "$enable_hours" | cut -d'-' -f1)
    end_hour=$(echo "$enable_hours" | cut -d'-' -f2)
    
    # Parse day range
    local start_day end_day
    start_day=$(echo "$enable_days" | cut -d'-' -f1)
    end_day=$(echo "$enable_days" | cut -d'-' -f2)
    
    # Check if current time is within allowed window
    local time_allowed=false
    local day_allowed=false
    
    if [[ "$current_hour" -ge "$start_hour" && "$current_hour" -lt "$end_hour" ]]; then
        time_allowed=true
    fi
    
    if [[ "$current_day" -ge "$start_day" && "$current_day" -le "$end_day" ]]; then
        day_allowed=true
    fi
    
    if [[ "$time_allowed" == "true" && "$day_allowed" == "true" ]]; then
        networksetup -setairportpower "$interface" on
        log_action "Wi-Fi enabled - within scheduled hours"
    else
        networksetup -setairportpower "$interface" off
        log_action "Wi-Fi disabled - outside scheduled hours"
    fi
}

# Conditional Wi-Fi control
apply_conditional_wifi_policy() {
    local interface="$1"
    local policy_name="$2"
    
    log_action "Applying conditional Wi-Fi policy: $policy_name"
    
    # Check battery level
    local battery_level
    battery_level=$(pmset -g batt | grep -o '[0-9]*%' | tr -d '%')
    
    # Check power source
    local power_source
    power_source=$(pmset -g ps | head -1 | grep -o "'.*'" | tr -d "'")
    
    # Check ethernet connection
    local ethernet_connected=false
    local ethernet_interfaces
    ethernet_interfaces=$(networksetup -listallhardwareports | grep -A 1 Ethernet | grep Device | awk '{print $2}')
    
    for eth_interface in $ethernet_interfaces; do
        local eth_status
        eth_status=$(ifconfig "$eth_interface" 2>/dev/null | grep "status: active")
        if [[ -n "$eth_status" ]]; then
            ethernet_connected=true
            break
        fi
    done
    
    # Apply conditional logic
    local should_enable_wifi=true
    
    # Disable Wi-Fi if ethernet is connected and policy requires it
    if [[ "$ethernet_connected" == "true" && "${DISABLE_WIFI_WITH_ETHERNET:-false}" == "true" ]]; then
        should_enable_wifi=false
        log_action "Wi-Fi disabled - Ethernet connection detected"
    fi
    
    # Disable Wi-Fi if battery is low and policy requires it
    if [[ -n "$battery_level" && "$battery_level" -lt "${MIN_BATTERY_FOR_WIFI:-20}" ]]; then
        should_enable_wifi=false
        log_action "Wi-Fi disabled - Low battery level: $battery_level%"
    fi
    
    # Enable/disable Wi-Fi based on conditions
    if [[ "$should_enable_wifi" == "true" ]]; then
        networksetup -setairportpower "$interface" on
        log_action "Wi-Fi enabled - Conditions met"
    else
        networksetup -setairportpower "$interface" off
        log_action "Wi-Fi disabled - Conditions not met"
    fi
}

# Security compliance check
check_wifi_security_compliance() {
    log_action "Performing Wi-Fi security compliance check"
    
    local compliance_issues=()
    local wifi_interface
    wifi_interface=$(networksetup -listallhardwareports | grep -A 1 Wi-Fi | grep Device | awk '{print $2}')
    
    if [[ -z "$wifi_interface" ]]; then
        log_action "ERROR: No Wi-Fi interface found for compliance check"
        return 1
    fi
    
    # Check if Wi-Fi is enabled when it should be disabled
    local power_status
    power_status=$(networksetup -getairportpower "$wifi_interface")
    
    if echo "$power_status" | grep -q "On"; then
        # Wi-Fi is enabled, check current network security
        local current_network
        current_network=$(networksetup -getairportnetwork "$wifi_interface" | cut -d' ' -f4-)
        
        if [[ "$current_network" != "You are not associated with an AirPort network." ]]; then
            log_action "Connected to network: $current_network"
            
            # Check if network is in approved list
            local approved_networks_file="$POLICY_DIR/approved_networks.list"
            if [[ -f "$approved_networks_file" ]]; then
                if ! grep -q "^$current_network$" "$approved_networks_file"; then
                    compliance_issues+=("Connected to non-approved network: $current_network")
                fi
            fi
            
            # Check for open networks
            if command -v airport >/dev/null 2>&1; then
                local network_security
                network_security=$(airport -I | grep "Security")
                if echo "$network_security" | grep -q "none"; then
                    compliance_issues+=("Connected to open/unsecured network")
                fi
            fi
        fi
    fi
    
    # Check for saved insecure networks
    local network_profiles
    network_profiles=$(networksetup -listpreferredwirelessnetworks "$wifi_interface" 2>/dev/null | tail -n +2)
    
    while IFS= read -r network; do
        if [[ -n "$network" ]]; then
            # Clean network name
            network=$(echo "$network" | sed 's/^[[:space:]]*//')
            
            # Check against blacklist
            local blacklist_file="$POLICY_DIR/blacklisted_networks.list"
            if [[ -f "$blacklist_file" ]]; then
                if grep -q "^$network$" "$blacklist_file"; then
                    compliance_issues+=("Blacklisted network in saved profiles: $network")
                fi
            fi
        fi
    done <<< "$network_profiles"
    
    # Generate compliance report
    if [[ ${#compliance_issues[@]} -eq 0 ]]; then
        log_action "✅ Wi-Fi security compliance check passed"
        return 0
    else
        log_action "❌ Wi-Fi security compliance violations found:"
        for issue in "${compliance_issues[@]}"; do
            log_action "  - $issue"
        done
        return 1
    fi
}

# Network profile management
manage_wifi_profiles() {
    local action="$1"
    local network_name="$2"
    local wifi_interface
    wifi_interface=$(networksetup -listallhardwareports | grep -A 1 Wi-Fi | grep Device | awk '{print $2}')
    
    if [[ -z "$wifi_interface" ]]; then
        log_action "ERROR: No Wi-Fi interface found"
        return 1
    fi
    
    case "$action" in
        "list")
            log_action "Listing saved Wi-Fi profiles"
            echo "=== Saved Wi-Fi Profiles ==="
            networksetup -listpreferredwirelessnetworks "$wifi_interface"
            ;;
        "remove")
            if [[ -z "$network_name" ]]; then
                log_action "ERROR: Network name required for removal"
                return 1
            fi
            
            log_action "Removing Wi-Fi profile: $network_name"
            networksetup -removepreferredwirelessnetwork "$wifi_interface" "$network_name"
            
            if [[ $? -eq 0 ]]; then
                log_action "✅ Wi-Fi profile removed: $network_name"
            else
                log_action "❌ Failed to remove Wi-Fi profile: $network_name"
                return 1
            fi
            ;;
        "removeall")
            log_action "Removing all saved Wi-Fi profiles"
            
            # Get list of networks and remove each one
            local networks
            networks=$(networksetup -listpreferredwirelessnetworks "$wifi_interface" 2>/dev/null | tail -n +2)
            
            while IFS= read -r network; do
                if [[ -n "$network" ]]; then
                    network=$(echo "$network" | sed 's/^[[:space:]]*//')
                    networksetup -removepreferredwirelessnetwork "$wifi_interface" "$network"
                    log_action "Removed profile: $network"
                fi
            done <<< "$networks"
            
            log_action "✅ All Wi-Fi profiles removed"
            ;;
        *)
            log_action "ERROR: Invalid action for profile management: $action"
            return 1
            ;;
    esac
}

# Power management optimization
optimize_wifi_power() {
    local optimization_level="${1:-balanced}"  # aggressive, balanced, conservative
    
    log_action "Applying Wi-Fi power optimization: $optimization_level"
    
    local wifi_interface
    wifi_interface=$(networksetup -listallhardwareports | grep -A 1 Wi-Fi | grep Device | awk '{print $2}')
    
    if [[ -z "$wifi_interface" ]]; then
        log_action "ERROR: No Wi-Fi interface found"
        return 1
    fi
    
    case "$optimization_level" in
        "aggressive")
            # Maximum power savings
            log_action "Applying aggressive power optimization"
            
            # Disable Wi-Fi when ethernet is connected
            local ethernet_connected=false
            local ethernet_interfaces
            ethernet_interfaces=$(networksetup -listallhardwareports | grep -A 1 Ethernet | grep Device | awk '{print $2}')
            
            for eth_interface in $ethernet_interfaces; do
                local eth_status
                eth_status=$(ifconfig "$eth_interface" 2>/dev/null | grep "status: active")
                if [[ -n "$eth_status" ]]; then
                    ethernet_connected=true
                    break
                fi
            done
            
            if [[ "$ethernet_connected" == "true" ]]; then
                networksetup -setairportpower "$wifi_interface" off
                log_action "Wi-Fi disabled - Ethernet connection detected"
            fi
            ;;
        "balanced")
            # Moderate power savings
            log_action "Applying balanced power optimization"
            
            # Check battery level and disable if very low
            local battery_level
            battery_level=$(pmset -g batt | grep -o '[0-9]*%' | tr -d '%')
            
            if [[ -n "$battery_level" && "$battery_level" -lt 10 ]]; then
                networksetup -setairportpower "$wifi_interface" off
                log_action "Wi-Fi disabled - Critical battery level: $battery_level%"
            fi
            ;;
        "conservative")
            # Minimal power optimization
            log_action "Applying conservative power optimization"
            
            # Only disable in extreme circumstances
            local battery_level
            battery_level=$(pmset -g batt | grep -o '[0-9]*%' | tr -d '%')
            
            if [[ -n "$battery_level" && "$battery_level" -lt 5 ]]; then
                networksetup -setairportpower "$wifi_interface" off
                log_action "Wi-Fi disabled - Emergency battery level: $battery_level%"
            fi
            ;;
        *)
            log_action "ERROR: Invalid optimization level: $optimization_level"
            return 1
            ;;
    esac
    
    return 0
}

# Generate Wi-Fi management report
generate_wifi_report() {
    local report_file="$BACKUP_DIR/wifi_management_report_$(date +%Y%m%d_%H%M%S).json"
    
    log_action "Generating Wi-Fi management report: $report_file"
    
    local wifi_interface
    wifi_interface=$(networksetup -listallhardwareports | grep -A 1 Wi-Fi | grep Device | awk '{print $2}')
    
    {
        echo "{"
        echo "  \"report_type\": \"wifi_management\","
        echo "  \"timestamp\": \"$(date -u +%Y-%m-%dT%H:%M:%SZ)\","
        echo "  \"hostname\": \"$(hostname)\","
        echo "  \"system_info\": {"
        echo "    \"macos_version\": \"$(sw_vers -productVersion)\","
        echo "    \"user\": \"$(whoami)\""
        echo "  },"
        
        if [[ -n "$wifi_interface" ]]; then
            local power_status current_network ip_address
            power_status=$(networksetup -getairportpower "$wifi_interface" | grep -o "On\|Off")
            current_network=$(networksetup -getairportnetwork "$wifi_interface" | cut -d' ' -f4-)
            ip_address=$(ifconfig "$wifi_interface" | grep "inet " | awk '{print $2}')
            
            echo "  \"wifi_status\": {"
            echo "    \"interface\": \"$wifi_interface\","
            echo "    \"power_status\": \"$power_status\","
            echo "    \"current_network\": \"$current_network\","
            echo "    \"ip_address\": \"${ip_address:-null}\""
            echo "  },"
        else
            echo "  \"wifi_status\": {"
            echo "    \"interface\": null,"
            echo "    \"power_status\": \"unavailable\","
            echo "    \"current_network\": null,"
            echo "    \"ip_address\": null"
            echo "  },"
        fi
        
        # Battery and power information
        local battery_level power_source
        battery_level=$(pmset -g batt | grep -o '[0-9]*%' | tr -d '%')
        power_source=$(pmset -g ps | head -1 | grep -o "'.*'" | tr -d "'")
        
        echo "  \"power_info\": {"
        echo "    \"battery_level\": ${battery_level:-null},"
        echo "    \"power_source\": \"${power_source:-unknown}\""
        echo "  },"
        
        # Network profiles
        echo "  \"saved_profiles\": ["
        if [[ -n "$wifi_interface" ]]; then
            local first_profile=true
            networksetup -listpreferredwirelessnetworks "$wifi_interface" 2>/dev/null | tail -n +2 | while IFS= read -r network; do
                if [[ -n "$network" ]]; then
                    network=$(echo "$network" | sed 's/^[[:space:]]*//')
                    if [[ "$first_profile" == "false" ]]; then
                        echo ","
                    fi
                    first_profile=false
                    echo -n "    \"$network\""
                fi
            done
        fi
        echo ""
        echo "  ]"
        echo "}"
    } > "$report_file"
    
    log_action "Wi-Fi management report generated: $report_file"
    echo "$report_file"
}

# Main management function
main() {
    local action="${1:-status}"
    local parameter1="$2"
    local parameter2="$3"
    
    setup_directories
    log_action "MacFleet Wi-Fi Control started with action: $action"
    
    case "$action" in
        "disable"|"off")
            turn_off_wifi_basic
            ;;
        "enable"|"on")
            turn_on_wifi "$parameter1"
            ;;
        "status")
            check_wifi_status
            ;;
        "scan")
            scan_wifi_networks "$parameter1" "$parameter2"
            ;;
        "discover")
            discover_wifi_interfaces
            ;;
        "policy")
            enforce_wifi_policy "$parameter1"
            ;;
        "compliance")
            check_wifi_security_compliance
            ;;
        "profiles")
            manage_wifi_profiles "$parameter1" "$parameter2"
            ;;
        "optimize")
            optimize_wifi_power "$parameter1"
            ;;
        "report")
            generate_wifi_report
            ;;
        *)
            check_wifi_status
            ;;
    esac
    
    log_action "MacFleet Wi-Fi Control completed with action: $action"
}

# Execute main function with all arguments
main "$@"

Wi-Fi Policy Templates

Corporate Wi-Fi Policy Configuration

# /etc/macfleet/wifi_policies/corporate_standard.policy
# MacFleet Corporate Wi-Fi Policy

# Policy action: disable, enable, scheduled, conditional
WIFI_POLICY_ACTION="conditional"

# Scheduled settings (for scheduled action)
WIFI_ENABLE_HOURS="08-18"    # 8 AM to 6 PM
WIFI_ENABLE_DAYS="1-5"       # Monday to Friday

# Conditional settings
DISABLE_WIFI_WITH_ETHERNET="true"
MIN_BATTERY_FOR_WIFI="15"

# Security settings
REQUIRE_WPA2_MINIMUM="true"
BLOCK_OPEN_NETWORKS="true"
AUTO_CONNECT_CORPORATE_ONLY="true"

# Power management
POWER_OPTIMIZATION_LEVEL="balanced"
AUTO_DISABLE_IDLE="true"
IDLE_TIMEOUT_MINUTES="30"

Security-Focused Wi-Fi Policy

# /etc/macfleet/wifi_policies/high_security.policy
# MacFleet High Security Wi-Fi Policy

WIFI_POLICY_ACTION="conditional"

# Security requirements
REQUIRE_WPA3_MINIMUM="true"
BLOCK_OPEN_NETWORKS="true"
BLOCK_WEP_NETWORKS="true"
APPROVED_NETWORKS_ONLY="true"

# Conditional disabling
DISABLE_WIFI_WITH_ETHERNET="true"
DISABLE_WIFI_IN_SECURE_AREAS="true"
MIN_BATTERY_FOR_WIFI="25"

# Monitoring
ENABLE_CONNECTION_LOGGING="true"
ALERT_ON_UNAPPROVED_NETWORKS="true"
SCAN_INTERVAL_MINUTES="5"

Power Conservation Policy

# /etc/macfleet/wifi_policies/power_saver.policy
# MacFleet Power Conservation Wi-Fi Policy

WIFI_POLICY_ACTION="conditional"

# Aggressive power saving
DISABLE_WIFI_WITH_ETHERNET="true"
MIN_BATTERY_FOR_WIFI="30"
POWER_OPTIMIZATION_LEVEL="aggressive"

# Scheduled disabling for night hours
WIFI_ENABLE_HOURS="07-22"    # 7 AM to 10 PM
WIFI_ENABLE_DAYS="1-7"       # All days

# Auto-disable features
AUTO_DISABLE_IDLE="true"
IDLE_TIMEOUT_MINUTES="15"
DISABLE_BACKGROUND_SCANNING="true"

Security and Compliance Functions

Network Whitelist Management

#!/bin/bash

# Manage approved Wi-Fi networks
manage_network_whitelist() {
    local action="$1"
    local network_name="$2"
    local whitelist_file="$POLICY_DIR/approved_networks.list"
    
    case "$action" in
        "add")
            if [[ -z "$network_name" ]]; then
                echo "ERROR: Network name required"
                return 1
            fi
            
            # Add network to whitelist
            if ! grep -q "^$network_name$" "$whitelist_file" 2>/dev/null; then
                echo "$network_name" >> "$whitelist_file"
                log_action "Added network to whitelist: $network_name"
            else
                log_action "Network already in whitelist: $network_name"
            fi
            ;;
        "remove")
            if [[ -z "$network_name" ]]; then
                echo "ERROR: Network name required"
                return 1
            fi
            
            # Remove network from whitelist
            if [[ -f "$whitelist_file" ]]; then
                grep -v "^$network_name$" "$whitelist_file" > "${whitelist_file}.tmp"
                mv "${whitelist_file}.tmp" "$whitelist_file"
                log_action "Removed network from whitelist: $network_name"
            fi
            ;;
        "list")
            echo "=== Approved Networks Whitelist ==="
            if [[ -f "$whitelist_file" ]]; then
                cat "$whitelist_file"
            else
                echo "No approved networks configured"
            fi
            ;;
        "enforce")
            enforce_network_whitelist
            ;;
        *)
            echo "ERROR: Invalid whitelist action: $action"
            return 1
            ;;
    esac
}

# Enforce network whitelist
enforce_network_whitelist() {
    local wifi_interface
    wifi_interface=$(networksetup -listallhardwareports | grep -A 1 Wi-Fi | grep Device | awk '{print $2}')
    
    if [[ -z "$wifi_interface" ]]; then
        log_action "ERROR: No Wi-Fi interface found"
        return 1
    fi
    
    # Get current network
    local current_network
    current_network=$(networksetup -getairportnetwork "$wifi_interface" | cut -d' ' -f4-)
    
    if [[ "$current_network" == "You are not associated with an AirPort network." ]]; then
        log_action "No active Wi-Fi connection"
        return 0
    fi
    
    # Check if current network is approved
    local whitelist_file="$POLICY_DIR/approved_networks.list"
    if [[ -f "$whitelist_file" ]]; then
        if grep -q "^$current_network$" "$whitelist_file"; then
            log_action "✅ Connected to approved network: $current_network"
            return 0
        else
            log_action "❌ Connected to non-approved network: $current_network"
            
            # Disconnect from non-approved network
            networksetup -setairportpower "$wifi_interface" off
            sleep 2
            networksetup -setairportpower "$wifi_interface" on
            
            log_action "Disconnected from non-approved network"
            return 1
        fi
    else
        log_action "⚠️  No whitelist configured - allowing all networks"
        return 0
    fi
}

# Example usage
# manage_network_whitelist "add" "CorporateWiFi"
# manage_network_whitelist "list"
# manage_network_whitelist "enforce"

Wi-Fi Audit and Monitoring

#!/bin/bash

# Comprehensive Wi-Fi audit
audit_wifi_configuration() {
    local audit_file="$BACKUP_DIR/wifi_audit_$(date +%Y%m%d_%H%M%S).txt"
    
    log_action "Performing comprehensive Wi-Fi audit: $audit_file"
    
    {
        echo "MacFleet Wi-Fi Configuration Audit"
        echo "=================================="
        echo "Generated: $(date)"
        echo "Hostname: $(hostname)"
        echo "Auditor: $(whoami)"
        echo ""
        
        # Wi-Fi interface information
        echo "WI-FI INTERFACE ANALYSIS:"
        echo "------------------------"
        discover_wifi_interfaces
        echo ""
        
        # Current connection status
        echo "CONNECTION STATUS:"
        echo "-----------------"
        check_wifi_status
        echo ""
        
        # Security compliance
        echo "SECURITY COMPLIANCE:"
        echo "-------------------"
        if check_wifi_security_compliance; then
            echo "✅ Security compliance check passed"
        else
            echo "❌ Security compliance violations detected"
        fi
        echo ""
        
        # Saved network profiles
        echo "SAVED NETWORK PROFILES:"
        echo "----------------------"
        manage_wifi_profiles "list"
        echo ""
        
        # Policy enforcement status
        echo "POLICY ENFORCEMENT:"
        echo "------------------"
        local policy_files
        policy_files=$(ls "$POLICY_DIR"/*.policy 2>/dev/null)
        
        if [[ -n "$policy_files" ]]; then
            for policy_file in $policy_files; do
                local policy_name
                policy_name=$(basename "$policy_file" .policy)
                echo "Policy: $policy_name"
                echo "  File: $policy_file"
                echo "  Status: $(if [[ -f "$policy_file" ]]; then echo "Active"; else echo "Inactive"; fi)"
            done
        else
            echo "No policies configured"
        fi
        echo ""
        
        # Power management status
        echo "POWER MANAGEMENT:"
        echo "----------------"
        local battery_level power_source
        battery_level=$(pmset -g batt | grep -o '[0-9]*%' | tr -d '%')
        power_source=$(pmset -g ps | head -1 | grep -o "'.*'" | tr -d "'")
        
        echo "Battery Level: ${battery_level:-Unknown}%"
        echo "Power Source: ${power_source:-Unknown}"
        echo ""
        
        # Recommendations
        echo "SECURITY RECOMMENDATIONS:"
        echo "------------------------"
        echo "• Implement approved network whitelist"
        echo "• Enable automatic disconnection from open networks"
        echo "• Configure scheduled Wi-Fi disable during off-hours"
        echo "• Implement battery-based power management"
        echo "• Regular audit of saved network profiles"
        echo "• Monitor for connections to unapproved networks"
        
    } > "$audit_file"
    
    log_action "Wi-Fi audit completed: $audit_file"
    echo "$audit_file"
}

audit_wifi_configuration

Important Technical Notes

NetworkSetup Command Reference

  • networksetup -setairportpower <device> on|off: Enable/disable Wi-Fi
  • networksetup -getairportpower <device>: Check Wi-Fi power status
  • networksetup -getairportnetwork <device>: Get current Wi-Fi network
  • networksetup -listpreferredwirelessnetworks <device>: List saved networks
  • networksetup -removepreferredwirelessnetwork <device> <network>: Remove saved network

Security Considerations

  1. Admin Privileges: Many network commands require admin access
  2. Network Isolation: Ensure proper network segmentation
  3. Profile Management: Regularly audit and clean saved network profiles
  4. Open Network Protection: Block connections to unsecured networks
  5. Compliance Monitoring: Implement continuous security compliance checking

Power Management Best Practices

  1. Battery Optimization: Disable Wi-Fi when battery is critically low
  2. Ethernet Priority: Prefer wired connections when available
  3. Scheduled Control: Implement time-based Wi-Fi policies
  4. Idle Management: Disable Wi-Fi during extended idle periods
  5. Resource Monitoring: Track power consumption patterns

Enterprise Use Cases

  1. Security-First Environments: Strict network whitelisting and compliance
  2. Power-Conscious Deployments: Battery optimization for mobile workers
  3. Scheduled Operations: Time-based Wi-Fi control for different work shifts
  4. Compliance Requirements: Audit trails and security monitoring
  5. Fleet Standardization: Consistent Wi-Fi policies across all devices

Remember to test all scripts on individual devices before deploying across your MacFleet environment, and ensure compliance with corporate security policies when implementing enterprise Wi-Fi control systems.

Website Access Control on macOS

Control website access across your MacFleet devices using advanced hosts file management, DNS filtering, and enterprise policy controls. This tutorial provides comprehensive tools for implementing organizational web access policies.

Understanding Website Access Control Methods

macOS offers multiple approaches for controlling website access:

  • Hosts File Management - Local DNS override for specific domains
  • DNS Configuration - Network-level filtering via custom DNS servers
  • System Proxy Settings - Route traffic through filtering proxies
  • Firewall Rules - Block specific IP addresses and port ranges

Basic Website Blocking

Block Single Website

#!/bin/bash

# Block access to a specific website
WEBSITE="www.facebook.com"

# Add entry to hosts file
echo "127.0.0.1 $WEBSITE" >> /etc/hosts
echo "127.0.0.1 facebook.com" >> /etc/hosts

echo "Blocked access to $WEBSITE"

Block Multiple Websites

#!/bin/bash

# Block multiple websites at once
BLOCKED_SITES=(
    "www.facebook.com"
    "facebook.com" 
    "m.facebook.com"
    "www.twitter.com"
    "twitter.com"
    "www.instagram.com"
    "instagram.com"
)

for site in "${BLOCKED_SITES[@]}"; do
    echo "127.0.0.1 $site" >> /etc/hosts
    echo "Blocked: $site"
done

echo "Website blocking completed"

Basic Website Unblocking

Unblock Single Website

#!/bin/bash

# Remove website from hosts file
WEBSITE="www.facebook.com"

/usr/bin/sed -i "" "/127.0.0.1 $WEBSITE/d" /etc/hosts
/usr/bin/sed -i "" "/127.0.0.1 facebook.com/d" /etc/hosts

echo "Unblocked access to $WEBSITE"

Unblock All Websites

#!/bin/bash

# Remove all blocking entries from hosts file
/usr/bin/sed -i "" '/^127.0.0.1.*[^localhost]/d' /etc/hosts

echo "All website blocks removed"

Enterprise Website Access Control System

#!/bin/bash

# MacFleet Enterprise Website Access Control
# Comprehensive web filtering and policy management system

# Configuration
MACFLEET_DIR="/etc/macfleet"
POLICIES_DIR="$MACFLEET_DIR/web_policies"
REPORTS_DIR="$MACFLEET_DIR/reports"
COMPLIANCE_DIR="$MACFLEET_DIR/compliance"
AUDIT_DIR="$MACFLEET_DIR/audit"
LOG_FILE="/var/log/macfleet_web_access.log"
BACKUP_DIR="$MACFLEET_DIR/backups"

# Create directory structure
create_directories() {
    local dirs=("$MACFLEET_DIR" "$POLICIES_DIR" "$REPORTS_DIR" "$COMPLIANCE_DIR" "$AUDIT_DIR" "$BACKUP_DIR")
    for dir in "${dirs[@]}"; do
        [[ ! -d "$dir" ]] && mkdir -p "$dir"
    done
}

# Logging function
log_action() {
    local message="$1"
    local timestamp=$(date '+%Y-%m-%d %H:%M:%S')
    echo "[$timestamp] $message" | tee -a "$LOG_FILE"
}

# Backup hosts file
backup_hosts() {
    local backup_file="$BACKUP_DIR/hosts_backup_$(date +%Y%m%d_%H%M%S)"
    cp /etc/hosts "$backup_file"
    log_action "Hosts file backed up to: $backup_file"
}

# Website Categories for Enterprise Filtering
declare -A WEBSITE_CATEGORIES=(
    ["social_media"]="facebook.com,twitter.com,instagram.com,linkedin.com,snapchat.com,tiktok.com,pinterest.com"
    ["entertainment"]="youtube.com,netflix.com,hulu.com,twitch.tv,spotify.com,reddit.com"
    ["gaming"]="steam.com,epic.com,roblox.com,minecraft.net,ea.com,ubisoft.com"
    ["shopping"]="amazon.com,ebay.com,etsy.com,shopify.com,aliexpress.com"
    ["news"]="cnn.com,bbc.com,reuters.com,bloomberg.com,wsj.com"
    ["adult_content"]="example.com"
    ["malicious"]="malware.com,phishing-site.com,trojan-host.com"
)

# Security Policies
declare -A SECURITY_POLICIES=(
    ["high_security"]="social_media,entertainment,gaming,shopping,adult_content,malicious"
    ["moderate_security"]="adult_content,malicious,gaming"
    ["minimal_security"]="adult_content,malicious"
    ["development_team"]="malicious"
    ["executive_access"]="malicious"
)

# Block websites by category
block_category() {
    local category="$1"
    local policy="$2"
    
    if [[ -z "${WEBSITE_CATEGORIES[$category]}" ]]; then
        log_action "ERROR: Unknown category: $category"
        return 1
    fi
    
    log_action "Blocking category: $category (Policy: $policy)"
    
    # Split comma-separated domains
    IFS=',' read -ra domains <<< "${WEBSITE_CATEGORIES[$category]}"
    
    for domain in "${domains[@]}"; do
        # Add multiple variations
        echo "127.0.0.1 $domain" >> /etc/hosts
        echo "127.0.0.1 www.$domain" >> /etc/hosts
        echo "127.0.0.1 m.$domain" >> /etc/hosts
        echo "127.0.0.1 mobile.$domain" >> /etc/hosts
        
        log_action "Blocked domain: $domain"
    done
    
    # Save policy metadata
    echo "category=$category,policy=$policy,timestamp=$(date),user=$(whoami)" >> "$POLICIES_DIR/applied_blocks.log"
}

# Apply security policy
apply_security_policy() {
    local policy="$1"
    
    if [[ -z "${SECURITY_POLICIES[$policy]}" ]]; then
        log_action "ERROR: Unknown security policy: $policy"
        return 1
    fi
    
    log_action "Applying security policy: $policy"
    backup_hosts
    
    # Clear existing blocks
    /usr/bin/sed -i "" '/^127.0.0.1.*[^localhost]/d' /etc/hosts
    
    # Apply categories for this policy
    IFS=',' read -ra categories <<< "${SECURITY_POLICIES[$policy]}"
    
    for category in "${categories[@]}"; do
        block_category "$category" "$policy"
    done
    
    # Flush DNS cache
    dscacheutil -flushcache
    killall -HUP mDNSResponder
    
    log_action "Security policy '$policy' applied successfully"
    
    # Generate compliance report
    generate_compliance_report "$policy"
}

# Advanced DNS-based filtering
configure_dns_filtering() {
    local filter_level="$1"
    
    log_action "Configuring DNS filtering: $filter_level"
    
    case "$filter_level" in
        "enterprise")
            # Use enterprise DNS servers with filtering
            networksetup -setdnsservers "Wi-Fi" 208.67.222.222 208.67.220.220
            networksetup -setdnsservers "Ethernet" 208.67.222.222 208.67.220.220
            ;;
        "family_safe")
            # Use family-safe DNS
            networksetup -setdnsservers "Wi-Fi" 208.67.222.123 208.67.220.123
            networksetup -setdnsservers "Ethernet" 208.67.222.123 208.67.220.123
            ;;
        "secure")
            # Use security-focused DNS
            networksetup -setdnsservers "Wi-Fi" 1.1.1.2 1.0.0.2
            networksetup -setdnsservers "Ethernet" 1.1.1.2 1.0.0.2
            ;;
        "default")
            # Reset to automatic DNS
            networksetup -setdnsservers "Wi-Fi" "Empty"
            networksetup -setdnsservers "Ethernet" "Empty"
            ;;
    esac
    
    log_action "DNS filtering configured: $filter_level"
}

# Whitelist management for essential business sites
manage_whitelist() {
    local action="$1"
    local domain="$2"
    local whitelist_file="$POLICIES_DIR/business_whitelist.txt"
    
    case "$action" in
        "add")
            if ! grep -q "^$domain$" "$whitelist_file" 2>/dev/null; then
                echo "$domain" >> "$whitelist_file"
                # Remove from hosts file if blocked
                /usr/bin/sed -i "" "/127.0.0.1.*$domain/d" /etc/hosts
                log_action "Added to whitelist: $domain"
            else
                log_action "Domain already whitelisted: $domain"
            fi
            ;;
        "remove")
            if [[ -f "$whitelist_file" ]]; then
                /usr/bin/sed -i "" "/^$domain$/d" "$whitelist_file"
                log_action "Removed from whitelist: $domain"
            fi
            ;;
        "list")
            if [[ -f "$whitelist_file" ]]; then
                echo "Business Whitelist:"
                cat "$whitelist_file"
            else
                echo "No whitelist found"
            fi
            ;;
    esac
}

# Emergency access mode
emergency_access() {
    local action="$1"
    local emergency_file="$POLICIES_DIR/emergency_mode.flag"
    
    case "$action" in
        "enable")
            # Backup current hosts and clear all blocks
            backup_hosts
            cp /etc/hosts "$BACKUP_DIR/hosts_before_emergency"
            /usr/bin/sed -i "" '/^127.0.0.1.*[^localhost]/d' /etc/hosts
            touch "$emergency_file"
            echo "emergency_enabled=$(date)" > "$emergency_file"
            log_action "EMERGENCY ACCESS ENABLED - All website blocks removed"
            ;;
        "disable")
            if [[ -f "$emergency_file" ]]; then
                rm "$emergency_file"
                # Restore previous configuration if available
                if [[ -f "$BACKUP_DIR/hosts_before_emergency" ]]; then
                    cp "$BACKUP_DIR/hosts_before_emergency" /etc/hosts
                    log_action "Emergency access disabled - Previous configuration restored"
                else
                    log_action "Emergency access disabled - Manual reconfiguration required"
                fi
            else
                log_action "Emergency access is not currently enabled"
            fi
            ;;
        "status")
            if [[ -f "$emergency_file" ]]; then
                echo "Emergency access: ENABLED"
                cat "$emergency_file"
            else
                echo "Emergency access: DISABLED"
            fi
            ;;
    esac
}

# Generate comprehensive compliance report
generate_compliance_report() {
    local policy="$1"
    local report_file="$REPORTS_DIR/web_access_compliance_$(date +%Y%m%d_%H%M%S).json"
    
    local blocked_domains=$(grep -c "^127.0.0.1" /etc/hosts 2>/dev/null || echo "0")
    local whitelist_count=0
    [[ -f "$POLICIES_DIR/business_whitelist.txt" ]] && whitelist_count=$(wc -l < "$POLICIES_DIR/business_whitelist.txt")
    
    cat > "$report_file" << EOF
{
  "report_metadata": {
    "timestamp": "$(date -u +%Y-%m-%dT%H:%M:%SZ)",
    "hostname": "$(hostname)",
    "policy_applied": "$policy",
    "report_version": "1.0"
  },
  "web_access_control": {
    "blocked_domains_count": $blocked_domains,
    "whitelisted_domains_count": $whitelist_count,
    "dns_filtering_active": $(networksetup -getdnsservers Wi-Fi | grep -q "208.67" && echo "true" || echo "false"),
    "emergency_mode": $([ -f "$POLICIES_DIR/emergency_mode.flag" ] && echo "true" || echo "false")
  },
  "security_policy": {
    "name": "$policy",
    "categories_blocked": "$(echo "${SECURITY_POLICIES[$policy]}" | tr ',' ' ')",
    "compliance_frameworks": ["SOX", "HIPAA", "NIST", "ISO27001"]
  },
  "system_status": {
    "hosts_file_size": $(wc -l < /etc/hosts),
    "last_dns_flush": "$(date -u +%Y-%m-%dT%H:%M:%SZ)",
    "backup_available": $([ -d "$BACKUP_DIR" ] && [ "$(ls -1 "$BACKUP_DIR"/hosts_backup_* 2>/dev/null | wc -l)" -gt 0 ] && echo "true" || echo "false")
  }
}
EOF
    
    log_action "Compliance report generated: $report_file"
    echo "Report saved to: $report_file"
}

# Health check and validation
perform_health_check() {
    echo "=== MacFleet Web Access Control Health Check ==="
    
    # Check hosts file integrity
    if [[ -f "/etc/hosts" ]]; then
        echo "✓ Hosts file exists"
        local hosts_size=$(wc -l < /etc/hosts)
        echo "  - Lines: $hosts_size"
    else
        echo "✗ Hosts file missing"
    fi
    
    # Check blocked domains
    local blocked_count=$(grep -c "^127.0.0.1" /etc/hosts 2>/dev/null || echo "0")
    echo "✓ Blocked domains: $blocked_count"
    
    # Check DNS configuration
    local dns_servers=$(networksetup -getdnsservers Wi-Fi)
    echo "✓ DNS servers: $dns_servers"
    
    # Check whitelist
    if [[ -f "$POLICIES_DIR/business_whitelist.txt" ]]; then
        local whitelist_count=$(wc -l < "$POLICIES_DIR/business_whitelist.txt")
        echo "✓ Whitelisted domains: $whitelist_count"
    else
        echo "○ No whitelist configured"
    fi
    
    # Check emergency mode
    if [[ -f "$POLICIES_DIR/emergency_mode.flag" ]]; then
        echo "⚠️  Emergency mode: ACTIVE"
    else
        echo "✓ Emergency mode: INACTIVE"
    fi
    
    # Check recent activity
    if [[ -f "$LOG_FILE" ]]; then
        local recent_entries=$(tail -5 "$LOG_FILE" | wc -l)
        echo "✓ Recent log entries: $recent_entries"
    fi
}

# Fleet deployment function
deploy_to_fleet() {
    local policy="$1"
    local fleet_file="$2"
    
    if [[ ! -f "$fleet_file" ]]; then
        log_action "ERROR: Fleet file not found: $fleet_file"
        return 1
    fi
    
    log_action "Starting fleet deployment of policy: $policy"
    
    while IFS= read -r host; do
        [[ -z "$host" || "$host" =~ ^#.*$ ]] && continue
        
        echo "Deploying to: $host"
        
        # Copy this script to remote host and execute
        ssh "$host" "bash -s" << EOF
#!/bin/bash
# Remote deployment of web access policy: $policy

# Create directories
mkdir -p /etc/macfleet/{web_policies,reports,compliance,audit,backups}

# Apply the policy (simplified for remote execution)
$(declare -p WEBSITE_CATEGORIES)
$(declare -p SECURITY_POLICIES)
$(type apply_security_policy | sed '1d')

apply_security_policy "$policy"
EOF
        
        if [[ $? -eq 0 ]]; then
            log_action "Successfully deployed to: $host"
        else
            log_action "Failed to deploy to: $host"
        fi
        
    done < "$fleet_file"
    
    log_action "Fleet deployment completed"
}

# Main execution function
main() {
    create_directories
    
    case "${1:-}" in
        "apply_policy")
            apply_security_policy "$2"
            ;;
        "block_category")
            backup_hosts
            block_category "$2" "manual"
            ;;
        "configure_dns")
            configure_dns_filtering "$2"
            ;;
        "whitelist")
            manage_whitelist "$2" "$3"
            ;;
        "emergency")
            emergency_access "$2"
            ;;
        "health_check")
            perform_health_check
            ;;
        "report")
            generate_compliance_report "${2:-manual}"
            ;;
        "deploy")
            deploy_to_fleet "$2" "$3"
            ;;
        "help"|*)
            echo "MacFleet Website Access Control System"
            echo ""
            echo "Usage: $0 <command> [options]"
            echo ""
            echo "Commands:"
            echo "  apply_policy <policy>     - Apply security policy (high_security|moderate_security|minimal_security|development_team|executive_access)"
            echo "  block_category <category> - Block website category (social_media|entertainment|gaming|shopping|news|adult_content|malicious)"
            echo "  configure_dns <level>     - Configure DNS filtering (enterprise|family_safe|secure|default)"
            echo "  whitelist <action> <domain> - Manage whitelist (add|remove|list)"
            echo "  emergency <action>        - Emergency access control (enable|disable|status)"
            echo "  health_check             - Perform system health check"
            echo "  report [policy]          - Generate compliance report"
            echo "  deploy <policy> <fleet_file> - Deploy policy to fleet"
            echo ""
            echo "Examples:"
            echo "  $0 apply_policy high_security"
            echo "  $0 whitelist add salesforce.com"
            echo "  $0 emergency enable"
            echo "  $0 health_check"
            ;;
    esac
}

# Execute main function
main "$@"

Business Hours and User-Friendly Controls

Time-Based Access Control

#!/bin/bash

# Apply different policies based on business hours
apply_time_based_policy() {
    local current_hour=$(date +%H)
    local day_of_week=$(date +%u)
    
    # Business hours: Monday-Friday 9 AM - 6 PM
    if [[ $day_of_week -le 5 ]] && [[ $current_hour -ge 9 ]] && [[ $current_hour -lt 18 ]]; then
        echo "Business hours detected - applying strict policy"
        apply_security_policy "high_security"
    else
        echo "Outside business hours - applying relaxed policy"
        apply_security_policy "moderate_security"
    fi
}

User Notification System

#!/bin/bash

# Notify user of website access changes
notify_user() {
    local message="$1"
    local title="MacFleet Web Access"
    
    # Use osascript for user notification
    osascript -e "display notification \"$message\" with title \"$title\" sound name \"Glass\""
    
    # Also log to system
    log_action "User notification: $message"
}

# Example usage
notify_user "Website access policy updated to High Security mode"

Important Security Considerations

  • Hosts file permissions should be restricted to prevent unauthorized modifications
  • DNS filtering provides network-level protection beyond local hosts file
  • Emergency access procedures should be documented and tested
  • Regular backups of hosts file and configuration are essential
  • Audit logging helps track policy changes and compliance

Compliance and Reporting

The enterprise system generates comprehensive reports for:

  • SOX Compliance - Financial services web access controls
  • HIPAA Requirements - Healthcare data protection policies
  • NIST Framework - Cybersecurity standards alignment
  • ISO 27001 - Information security management

Testing and Validation

Before deploying to production:

  1. Test individual commands on isolated systems
  2. Verify DNS resolution after applying policies
  3. Confirm business applications remain accessible
  4. Test emergency procedures and restoration
  5. Validate compliance reporting accuracy

This comprehensive system transforms basic website blocking into an enterprise-grade access control platform with advanced policy management, compliance reporting, and fleet deployment capabilities.