Tutorial

Nuevas actualizaciones y mejoras para Macfleet.

Aviso importante

Los ejemplos de código y scripts proporcionados en estos tutoriales son solo para propósitos educativos. Macfleet no es responsable de ningún problema, daño o vulnerabilidad de seguridad que pueda surgir del uso, modificación o implementación de estos ejemplos. Siempre revisa y prueba el código en un entorno seguro antes de usarlo en sistemas de producción.

System Information Management on macOS

Collect and analyze comprehensive system information across your MacFleet devices using advanced system profiling, automated data collection, and enterprise-grade analytics. This tutorial provides powerful tools for implementing organizational device inventory, monitoring, and compliance reporting.

Understanding macOS System Information

macOS provides several tools for system information gathering:

  • system_profiler - Comprehensive system information collection
  • uname - Basic system and kernel information
  • sw_vers - Software version information
  • hwpref - Hardware preference data
  • ioreg - I/O Registry hardware information
  • System Information.app - GUI system information interface

Basic System Information Operations

Complete System Information

#!/bin/bash

# Get complete system information
echo "=== Complete System Information ==="
system_profiler

echo "System information collection completed"

List Available Data Types

#!/bin/bash

# List all available system profiler data types
echo "=== Available Data Types ==="
system_profiler --listDataTypes

echo "Data types listing completed"

Specific System Information

#!/bin/bash

# Get specific system information
DATA_TYPE="${1:-SPHardwareDataType}"

echo "=== $DATA_TYPE Information ==="
system_profiler "$DATA_TYPE"

echo "Specific system information retrieved"

Save System Report to File

#!/bin/bash

# Save system information to file
REPORT_FILE="${1:-/tmp/system_report_$(date +%Y%m%d_%H%M%S).txt}"

echo "=== Saving System Report ==="
system_profiler > "$REPORT_FILE"

echo "System report saved to: $REPORT_FILE"

Enterprise System Information Management System

#!/bin/bash

# MacFleet Enterprise System Information Management System
# Comprehensive system data collection, analysis, and monitoring

# Configuration
MACFLEET_DIR="/etc/macfleet"
SYSINFO_DIR="$MACFLEET_DIR/system_information"
REPORTS_DIR="$MACFLEET_DIR/reports"
COMPLIANCE_DIR="$MACFLEET_DIR/compliance"
AUDIT_DIR="$MACFLEET_DIR/audit"
LOG_FILE="/var/log/macfleet_system_information.log"
POLICIES_DIR="$MACFLEET_DIR/system_policies"
INVENTORY_DIR="$MACFLEET_DIR/inventory"

# Create directory structure
create_directories() {
    local dirs=("$MACFLEET_DIR" "$SYSINFO_DIR" "$REPORTS_DIR" "$COMPLIANCE_DIR" "$AUDIT_DIR" "$POLICIES_DIR" "$INVENTORY_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"
}

# System Information Categories for Enterprise Management
declare -A SYSTEM_CATEGORIES=(
    ["hardware_overview"]="SPHardwareDataType,SPMemoryDataType,SPStorageDataType"
    ["software_inventory"]="SPSoftwareDataType,SPApplicationsDataType,SPExtensionsDataType"
    ["network_configuration"]="SPNetworkDataType,SPBluetoothDataType,SPWWANDataType"
    ["security_configuration"]="SPFirewallDataType,SPManagedClientDataType,SPConfigurationProfileDataType"
    ["peripherals"]="SPUSBDataType,SPThunderboltDataType,SPAudioDataType,SPDisplaysDataType"
    ["system_diagnostics"]="SPPowerDataType,SPLogsDataType,SPDiagnosticsDataType"
    ["enterprise_management"]="SPManagedClientDataType,SPConfigurationProfileDataType,SPCertificatesDataType"
)

# Data Collection Policies
declare -A COLLECTION_POLICIES=(
    ["comprehensive"]="all_data_types,full_detail,include_sensitive,export_json"
    ["security_focused"]="security_data,certificates,firewall_config,managed_profiles"
    ["hardware_inventory"]="hardware_overview,storage_details,memory_config,peripherals"
    ["software_audit"]="applications,extensions,system_software,preferences"
    ["network_assessment"]="network_interfaces,bluetooth_devices,wireless_config"
    ["compliance_report"]="security_config,certificates,managed_profiles,audit_data"
)

# System Health Monitoring Thresholds
declare -A HEALTH_THRESHOLDS=(
    ["cpu_temperature_warning"]=80
    ["memory_pressure_warning"]=80
    ["storage_usage_warning"]=85
    ["battery_cycle_warning"]=800
    ["uptime_excessive_hours"]=168  # 1 week
)

# Comprehensive system information collection
collect_system_information() {
    local collection_policy="$1"
    local output_format="${2:-json}"
    local include_sensitive="${3:-false}"
    local collection_id="sysinfo_$(date +%Y%m%d_%H%M%S)"
    local output_file="$SYSINFO_DIR/${collection_id}.${output_format}"
    
    log_action "Starting system information collection: $collection_policy"
    
    # Initialize collection metadata
    local hostname=$(hostname)
    local serial_number=$(system_profiler SPHardwareDataType | grep "Serial Number" | awk '{print $4}')
    local model_identifier=$(system_profiler SPHardwareDataType | grep "Model Identifier" | awk '{print $3}')
    local os_version=$(sw_vers -productVersion)
    local build_version=$(sw_vers -buildVersion)
    local uptime=$(uptime | awk '{print $3,$4}' | sed 's/,//')
    
    # Collect data based on policy
    local collected_data=""
    local data_types=""
    
    case "$collection_policy" in
        "comprehensive")
            data_types=$(system_profiler --listDataTypes | tr '\n' ' ')
            ;;
        "security_focused")
            data_types="SPFirewallDataType SPManagedClientDataType SPConfigurationProfileDataType SPCertificatesDataType"
            ;;
        "hardware_inventory")
            data_types="SPHardwareDataType SPMemoryDataType SPStorageDataType SPUSBDataType SPDisplaysDataType SPAudioDataType"
            ;;
        "software_audit")
            data_types="SPSoftwareDataType SPApplicationsDataType SPExtensionsDataType SPPrefPaneDataType"
            ;;
        "network_assessment")
            data_types="SPNetworkDataType SPBluetoothDataType SPWWANDataType SPAirPortDataType"
            ;;
        "compliance_report")
            data_types="SPManagedClientDataType SPConfigurationProfileDataType SPCertificatesDataType SPFirewallDataType"
            ;;
    esac
    
    # Collect data for each specified type
    for data_type in $data_types; do
        [[ -z "$data_type" ]] && continue
        
        log_action "Collecting data type: $data_type"
        
        if [[ "$output_format" == "json" ]]; then
            local type_data=$(system_profiler -json "$data_type" 2>/dev/null)
            if [[ -n "$type_data" && "$type_data" != "null" ]]; then
                collected_data="$collected_data\"$data_type\":$type_data,"
            fi
        else
            local type_data=$(system_profiler "$data_type" 2>/dev/null)
            if [[ -n "$type_data" ]]; then
                collected_data="$collected_data\n=== $data_type ===\n$type_data\n"
            fi
        fi
    done
    
    # Additional system metrics
    local additional_metrics=""
    if [[ "$include_sensitive" == "true" || "$collection_policy" == "comprehensive" ]]; then
        local cpu_info=$(sysctl -n machdep.cpu.brand_string)
        local memory_total=$(system_profiler SPHardwareDataType | grep "Memory:" | awk '{print $2,$3}')
        local storage_info=$(df -h / | awk 'NR==2 {print $2,$3,$4,$5}')
        local network_interfaces=$(ifconfig | grep "^[a-z]" | awk '{print $1}' | sed 's/:$//' | tr '\n' ' ')
        local running_processes=$(ps aux | wc -l)
        local logged_in_users=$(who | wc -l)
        
        additional_metrics="{\"cpu_info\":\"$cpu_info\",\"memory_total\":\"$memory_total\",\"storage_info\":\"$storage_info\",\"network_interfaces\":\"$network_interfaces\",\"running_processes\":$running_processes,\"logged_in_users\":$logged_in_users}"
    fi
    
    # Create structured output
    if [[ "$output_format" == "json" ]]; then
        # Remove trailing comma from collected data
        collected_data="${collected_data%,}"
        
        cat > "$output_file" << EOF
{
  "collection_metadata": {
    "collection_id": "$collection_id",
    "timestamp": "$(date -u +%Y-%m-%dT%H:%M:%SZ)",
    "policy": "$collection_policy",
    "hostname": "$hostname",
    "serial_number": "$serial_number",
    "model_identifier": "$model_identifier",
    "os_version": "$os_version",
    "build_version": "$build_version",
    "uptime": "$uptime"
  },
  "system_data": {$collected_data},
  "additional_metrics": $additional_metrics,
  "collection_summary": {
    "data_types_collected": $(echo "$data_types" | wc -w),
    "include_sensitive": "$include_sensitive",
    "collection_size_bytes": $(wc -c < "$output_file" 2>/dev/null || echo "0")
  }
}
EOF
    else
        cat > "$output_file" << EOF
=== MacFleet System Information Report ===
Collection ID: $collection_id
Timestamp: $(date)
Policy: $collection_policy
Hostname: $hostname
Serial Number: $serial_number
Model: $model_identifier
OS Version: $os_version ($build_version)
Uptime: $uptime

$collected_data
EOF
    fi
    
    log_action "System information collection completed: $output_file"
    echo "$output_file"
}

# System health analysis
analyze_system_health() {
    local analysis_type="$1"
    local health_report="$REPORTS_DIR/system_health_$(date +%Y%m%d_%H%M%S).json"
    
    log_action "Starting system health analysis: $analysis_type"
    
    # Collect basic health metrics
    local cpu_temp=$(sudo powermetrics -n 1 -s cpu_power | grep "CPU die temperature" | awk '{print $4}' 2>/dev/null || echo "0")
    local memory_pressure=$(vm_stat | grep "Pages compressed" | awk '{print $3}' | sed 's/\.//' | head -1)
    local storage_usage=$(df -h / | awk 'NR==2 {print $5}' | sed 's/%//')
    local uptime_seconds=$(sysctl -n kern.boottime | awk '{print $4}' | sed 's/,//')
    local current_time=$(date +%s)
    local uptime_hours=$(( (current_time - uptime_seconds) / 3600 ))
    
    # System load analysis
    local load_average=$(uptime | awk -F'load average:' '{print $2}' | awk '{print $1}' | sed 's/,//')
    local cpu_cores=$(sysctl -n hw.ncpu)
    local load_per_core=$(echo "scale=2; $load_average / $cpu_cores" | bc -l 2>/dev/null || echo "0")
    
    # Battery information (if available)
    local battery_cycle_count=0
    local battery_condition="Unknown"
    if system_profiler SPPowerDataType | grep -q "Cycle Count"; then
        battery_cycle_count=$(system_profiler SPPowerDataType | grep "Cycle Count" | awk '{print $3}')
        battery_condition=$(system_profiler SPPowerDataType | grep "Condition" | awk '{print $2}')
    fi
    
    # Determine health status
    local health_status="healthy"
    local health_alerts=""
    
    if [[ $(echo "$cpu_temp > ${HEALTH_THRESHOLDS[cpu_temperature_warning]}" | bc -l 2>/dev/null) -eq 1 ]]; then
        health_status="warning"
        health_alerts="$health_alerts\"High CPU temperature: ${cpu_temp}°C\","
    fi
    
    if [[ $storage_usage -gt ${HEALTH_THRESHOLDS[storage_usage_warning]} ]]; then
        health_status="warning"
        health_alerts="$health_alerts\"High storage usage: ${storage_usage}%\","
    fi
    
    if [[ $battery_cycle_count -gt ${HEALTH_THRESHOLDS[battery_cycle_warning]} ]]; then
        health_status="warning"
        health_alerts="$health_alerts\"High battery cycle count: $battery_cycle_count\","
    fi
    
    if [[ $uptime_hours -gt ${HEALTH_THRESHOLDS[uptime_excessive_hours]} ]]; then
        health_status="attention"
        health_alerts="$health_alerts\"Excessive uptime: ${uptime_hours} hours\","
    fi
    
    # Remove trailing comma
    health_alerts="${health_alerts%,}"
    
    # Create health report
    cat > "$health_report" << EOF
{
  "system_health_analysis": {
    "timestamp": "$(date -u +%Y-%m-%dT%H:%M:%SZ)",
    "analysis_type": "$analysis_type",
    "health_status": "$health_status",
    "device_info": {
      "hostname": "$(hostname)",
      "serial_number": "$(system_profiler SPHardwareDataType | grep "Serial Number" | awk '{print $4}')",
      "model": "$(system_profiler SPHardwareDataType | grep "Model Identifier" | awk '{print $3}')",
      "os_version": "$(sw_vers -productVersion)"
    }
  },
  "health_metrics": {
    "cpu_temperature_celsius": "$cpu_temp",
    "memory_pressure_pages": "$memory_pressure",
    "storage_usage_percent": $storage_usage,
    "uptime_hours": $uptime_hours,
    "load_average": "$load_average",
    "load_per_core": "$load_per_core",
    "cpu_cores": $cpu_cores,
    "battery_cycle_count": $battery_cycle_count,
    "battery_condition": "$battery_condition"
  },
  "health_alerts": [$health_alerts],
  "recommendations": [
    $([ "$health_status" != "healthy" ] && echo "\"Address health alerts for optimal performance\",")
    $([ $uptime_hours -gt 72 ] && echo "\"Consider system restart for optimal performance\",")
    $([ $storage_usage -gt 80 ] && echo "\"Review storage usage and cleanup if necessary\",")
    "\"Regular health monitoring recommended\""
  ]
}
EOF
    
    if [[ "$health_status" != "healthy" ]]; then
        log_action "HEALTH WARNING: System health issues detected - $health_status"
    fi
    
    log_action "System health analysis completed: $health_report"
    echo "$health_report"
}

# Enterprise device inventory management
manage_device_inventory() {
    local inventory_action="$1"
    local device_group="${2:-default}"
    local inventory_file="$INVENTORY_DIR/device_inventory_${device_group}.json"
    
    log_action "Managing device inventory: $inventory_action for group $device_group"
    
    case "$inventory_action" in
        "register")
            # Register device in inventory
            local device_data=$(collect_system_information "hardware_inventory" "json" "false")
            local hostname=$(hostname)
            local serial_number=$(system_profiler SPHardwareDataType | grep "Serial Number" | awk '{print $4}')
            local model=$(system_profiler SPHardwareDataType | grep "Model Name" | awk -F': ' '{print $2}')
            local mac_address=$(ifconfig en0 | grep ether | awk '{print $2}')
            
            # Update inventory database
            if [[ -f "$inventory_file" ]]; then
                # Update existing inventory
                jq --arg hostname "$hostname" --arg serial "$serial_number" --arg model "$model" --arg mac "$mac_address" --arg timestamp "$(date -u +%Y-%m-%dT%H:%M:%SZ)" \
                   '.devices[$hostname] = {serial_number: $serial, model: $model, mac_address: $mac, last_updated: $timestamp, status: "active"}' \
                   "$inventory_file" > "${inventory_file}.tmp" && mv "${inventory_file}.tmp" "$inventory_file"
            else
                # Create new inventory
                jq -n --arg hostname "$hostname" --arg serial "$serial_number" --arg model "$model" --arg mac "$mac_address" --arg timestamp "$(date -u +%Y-%m-%dT%H:%M:%SZ)" \
                   '{inventory_metadata: {group: "'$device_group'", created: $timestamp}, devices: {($hostname): {serial_number: $serial, model: $model, mac_address: $mac, last_updated: $timestamp, status: "active"}}}' \
                   > "$inventory_file"
            fi
            
            log_action "Device registered in inventory: $hostname ($serial_number)"
            ;;
            
        "update")
            # Update device information
            local hostname=$(hostname)
            if [[ -f "$inventory_file" ]] && jq -e ".devices[\"$hostname\"]" "$inventory_file" >/dev/null; then
                jq --arg hostname "$hostname" --arg timestamp "$(date -u +%Y-%m-%dT%H:%M:%SZ)" \
                   '.devices[$hostname].last_updated = $timestamp | .devices[$hostname].status = "active"' \
                   "$inventory_file" > "${inventory_file}.tmp" && mv "${inventory_file}.tmp" "$inventory_file"
                log_action "Device inventory updated: $hostname"
            else
                log_action "Device not found in inventory, registering: $hostname"
                manage_device_inventory "register" "$device_group"
            fi
            ;;
            
        "list")
            # List devices in inventory
            if [[ -f "$inventory_file" ]]; then
                echo "=== Device Inventory for Group: $device_group ==="
                jq -r '.devices | to_entries[] | "\(.key): \(.value.model) (\(.value.serial_number)) - \(.value.status)"' "$inventory_file"
            else
                echo "No inventory found for group: $device_group"
            fi
            ;;
            
        "remove")
            # Remove device from inventory
            local hostname=$(hostname)
            if [[ -f "$inventory_file" ]]; then
                jq --arg hostname "$hostname" 'del(.devices[$hostname])' "$inventory_file" > "${inventory_file}.tmp" && mv "${inventory_file}.tmp" "$inventory_file"
                log_action "Device removed from inventory: $hostname"
            fi
            ;;
    esac
}

# Compliance and security reporting
generate_compliance_report() {
    local compliance_framework="$1"
    local report_file="$COMPLIANCE_DIR/compliance_${compliance_framework}_$(date +%Y%m%d_%H%M%S).json"
    
    log_action "Generating compliance report: $compliance_framework"
    
    # Collect security-relevant system information
    local security_data=$(collect_system_information "security_focused" "json" "true")
    
    # Check specific compliance requirements
    local filevault_status=$(fdesetup status | grep -q "On" && echo "enabled" || echo "disabled")
    local firewall_status=$(sudo /usr/libexec/ApplicationFirewall/socketfilterfw --getglobalstate | grep -q "enabled" && echo "enabled" || echo "disabled")
    local gatekeeper_status=$(spctl --status | grep -q "enabled" && echo "enabled" || echo "disabled")
    local sip_status=$(csrutil status | grep -q "enabled" && echo "enabled" || echo "disabled")
    local secure_boot_status=$(nvram 94b73556-2197-4702-82a8-3e1337dafbfb:AppleSecureBootPolicy 2>/dev/null | grep -q "2" && echo "full" || echo "reduced")
    
    # Software update status
    local auto_update_status=$(defaults read /Library/Preferences/com.apple.SoftwareUpdate AutomaticCheckEnabled 2>/dev/null || echo "0")
    local last_update_check=$(defaults read /Library/Preferences/com.apple.SoftwareUpdate LastSuccessfulDate 2>/dev/null || echo "Unknown")
    
    # Certificate information
    local certificate_count=$(security find-certificate -a | grep "labl" | wc -l)
    local expired_certificates=$(security find-certificate -a -p | openssl x509 -noout -checkend 0 2>/dev/null | grep -c "will expire" || echo "0")
    
    # Create compliance report based on framework
    case "$compliance_framework" in
        "nist")
            cat > "$report_file" << EOF
{
  "compliance_report": {
    "framework": "NIST Cybersecurity Framework",
    "timestamp": "$(date -u +%Y-%m-%dT%H:%M:%SZ)",
    "device_info": {
      "hostname": "$(hostname)",
      "serial_number": "$(system_profiler SPHardwareDataType | grep "Serial Number" | awk '{print $4}')",
      "os_version": "$(sw_vers -productVersion)"
    }
  },
  "security_controls": {
    "identify": {
      "asset_management": "implemented",
      "system_inventory": "automated"
    },
    "protect": {
      "access_control": "$([ "$gatekeeper_status" == "enabled" ] && echo "implemented" || echo "needs_attention")",
      "data_security": "$([ "$filevault_status" == "enabled" ] && echo "implemented" || echo "needs_attention")",
      "protective_technology": "$([ "$firewall_status" == "enabled" ] && echo "implemented" || echo "needs_attention")"
    },
    "detect": {
      "security_monitoring": "basic",
      "malicious_code_protection": "$([ "$gatekeeper_status" == "enabled" ] && echo "implemented" || echo "needs_attention")"
    },
    "respond": {
      "incident_response": "manual",
      "communications": "standard"
    },
    "recover": {
      "recovery_planning": "$([ "$filevault_status" == "enabled" ] && echo "implemented" || echo "needs_attention")",
      "backup_procedures": "time_machine"
    }
  },
  "technical_controls": {
    "filevault_encryption": "$filevault_status",
    "firewall_protection": "$firewall_status",
    "gatekeeper_protection": "$gatekeeper_status",
    "system_integrity_protection": "$sip_status",
    "secure_boot": "$secure_boot_status",
    "automatic_updates": "$([ "$auto_update_status" == "1" ] && echo "enabled" || echo "disabled")",
    "certificate_management": {
      "total_certificates": $certificate_count,
      "expired_certificates": $expired_certificates
    }
  }
}
EOF
            ;;
            
        "hipaa")
            cat > "$report_file" << EOF
{
  "compliance_report": {
    "framework": "HIPAA Security Rule",
    "timestamp": "$(date -u +%Y-%m-%dT%H:%M:%SZ)",
    "device_info": {
      "hostname": "$(hostname)",
      "serial_number": "$(system_profiler SPHardwareDataType | grep "Serial Number" | awk '{print $4}')",
      "os_version": "$(sw_vers -productVersion)"
    }
  },
  "administrative_safeguards": {
    "access_management": "policy_required",
    "workforce_training": "policy_required",
    "contingency_plan": "policy_required"
  },
  "physical_safeguards": {
    "facility_access": "policy_required",
    "workstation_security": "$([ "$filevault_status" == "enabled" ] && echo "implemented" || echo "needs_attention")",
    "device_controls": "$([ "$gatekeeper_status" == "enabled" ] && echo "implemented" || echo "needs_attention")"
  },
  "technical_safeguards": {
    "access_control": "$([ "$gatekeeper_status" == "enabled" ] && echo "implemented" || echo "needs_attention")",
    "audit_controls": "basic_logging",
    "integrity": "$([ "$sip_status" == "enabled" ] && echo "implemented" || echo "needs_attention")",
    "transmission_security": "$([ "$firewall_status" == "enabled" ] && echo "implemented" || echo "needs_attention")",
    "encryption": "$([ "$filevault_status" == "enabled" ] && echo "implemented" || echo "needs_attention")"
  }
}
EOF
            ;;
    esac
    
    log_action "Compliance report generated: $report_file"
    echo "Compliance report saved to: $report_file"
}

# Automated system monitoring and alerting
monitor_system_continuously() {
    local monitoring_interval="${1:-600}"  # 10 minutes default
    local alert_threshold="${2:-warning}"  # warning level default
    
    log_action "Starting continuous system monitoring (interval: ${monitoring_interval}s, threshold: $alert_threshold)"
    
    while true; do
        # Perform health analysis
        local health_report=$(analyze_system_health "continuous")
        local health_status=$(jq -r '.system_health_analysis.health_status' "$health_report" 2>/dev/null || echo "unknown")
        
        if [[ "$health_status" != "healthy" && "$health_status" != "unknown" ]]; then
            local hostname=$(hostname)
            log_action "SYSTEM ALERT: Health status is $health_status for $hostname"
            
            # Send system notification
            osascript -e "display notification \"System health: $health_status\" with title \"MacFleet System Monitor\""
            
            # Generate detailed report if critical
            if [[ "$health_status" == "critical" ]]; then
                collect_system_information "comprehensive" "json" "false"
            fi
        fi
        
        # Update device inventory
        manage_device_inventory "update" "monitored"
        
        # Log current status
        log_action "System monitoring check completed - Status: $health_status"
        
        sleep "$monitoring_interval"
    done
}

# Fleet deployment and management
deploy_to_fleet() {
    local deployment_action="$1"
    local fleet_file="$2"
    local deployment_policy="${3:-standard}"
    
    if [[ ! -f "$fleet_file" ]]; then
        log_action "ERROR: Fleet file not found: $fleet_file"
        return 1
    fi
    
    log_action "Deploying system information management to fleet: $deployment_action"
    
    while IFS= read -r host; do
        [[ -z "$host" || "$host" =~ ^#.*$ ]] && continue
        
        echo "Deploying to: $host"
        
        # Deploy system information management to remote host
        ssh "$host" "bash -s" << EOF
#!/bin/bash
# Remote deployment of system information management: $deployment_policy

# Create MacFleet directories
mkdir -p /etc/macfleet/{system_information,reports,compliance,audit,system_policies,inventory}

# Collect initial system information
echo "Collecting initial system information on \$(hostname)"

case "$deployment_policy" in
    "comprehensive")
        echo "Deploying comprehensive system monitoring"
        ;;
    "security_focused")
        echo "Deploying security-focused system monitoring"
        ;;
    "compliance_audit")
        echo "Deploying compliance audit configuration"
        ;;
esac

echo "System information management deployed on \$(hostname)"
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"
}

# Health check and system validation
perform_system_health_check() {
    echo "=== MacFleet System Information Management Health Check ==="
    
    # Check system_profiler availability
    if command -v system_profiler >/dev/null 2>&1; then
        echo "✓ system_profiler: Available"
    else
        echo "✗ system_profiler: Not available"
    fi
    
    # Check system information accessibility
    local hardware_info=$(system_profiler SPHardwareDataType 2>/dev/null)
    if [[ -n "$hardware_info" ]]; then
        echo "✓ Hardware information: Accessible"
    else
        echo "⚠️  Hardware information: Limited access"
    fi
    
    # Check security status
    local filevault_status=$(fdesetup status)
    if echo "$filevault_status" | grep -q "On"; then
        echo "✓ FileVault: Enabled"
    else
        echo "○ FileVault: Disabled"
    fi
    
    # Check firewall status
    if sudo /usr/libexec/ApplicationFirewall/socketfilterfw --getglobalstate | grep -q "enabled"; then
        echo "✓ Firewall: Enabled"
    else
        echo "○ Firewall: Disabled"
    fi
    
    # Check Gatekeeper status
    if spctl --status | grep -q "enabled"; then
        echo "✓ Gatekeeper: Enabled"
    else
        echo "○ Gatekeeper: Disabled"
    fi
    
    # Check System Integrity Protection
    if csrutil status | grep -q "enabled"; then
        echo "✓ SIP: Enabled"
    else
        echo "⚠️  SIP: Disabled"
    fi
    
    # Check available storage space
    local available_space=$(df -h / | awk 'NR==2 {print $4}')
    echo "✓ Available storage: $available_space"
    
    # Check system uptime
    local uptime_info=$(uptime)
    echo "✓ System uptime: $uptime_info"
}

# Main execution function
main() {
    create_directories
    
    case "${1:-}" in
        "collect")
            collect_system_information "${2:-comprehensive}" "${3:-json}" "${4:-false}"
            ;;
        "analyze_health")
            analyze_system_health "${2:-standard}"
            ;;
        "inventory")
            manage_device_inventory "${2:-list}" "${3:-default}"
            ;;
        "compliance")
            generate_compliance_report "${2:-nist}"
            ;;
        "monitor")
            monitor_system_continuously "${2:-600}" "${3:-warning}"
            ;;
        "deploy_fleet")
            deploy_to_fleet "${2:-install}" "$3" "${4:-standard}"
            ;;
        "health_check")
            perform_system_health_check
            ;;
        "help"|*)
            echo "MacFleet Enterprise System Information Management System"
            echo ""
            echo "Usage: $0 <command> [options]"
            echo ""
            echo "Commands:"
            echo "  collect [policy] [format] [sensitive]    - Collect system information (comprehensive|security_focused|hardware_inventory|software_audit|network_assessment|compliance_report) [json|text] [true|false]"
            echo "  analyze_health [type]                    - Analyze system health (standard|detailed|continuous)"
            echo "  inventory <action> [group]               - Manage device inventory (register|update|list|remove) [group_name]"
            echo "  compliance [framework]                   - Generate compliance report (nist|hipaa|sox|iso27001)"
            echo "  monitor [interval] [threshold]           - Continuous monitoring (interval in seconds) (healthy|warning|critical)"
            echo "  deploy_fleet <action> <fleet_file> [policy] - Deploy to fleet (install|update|remove) [comprehensive|security_focused|compliance_audit]"
            echo "  health_check                             - Perform system health check"
            echo ""
            echo "Examples:"
            echo "  $0 collect comprehensive json false"
            echo "  $0 analyze_health detailed"
            echo "  $0 inventory register production"
            echo "  $0 compliance nist"
            echo "  $0 monitor 300 warning"
            echo "  $0 health_check"
            ;;
    esac
}

# Execute main function
main "$@"

System Information Data Types

The enterprise system supports comprehensive data type collection:

CategoryData TypesUse Case
Hardware OverviewSPHardwareDataType, SPMemoryDataType, SPStorageDataTypeAsset inventory and capacity planning
Software InventorySPSoftwareDataType, SPApplicationsDataType, SPExtensionsDataTypeLicense management and security auditing
Network ConfigurationSPNetworkDataType, SPBluetoothDataType, SPWWANDataTypeNetwork security and connectivity analysis
Security ConfigurationSPFirewallDataType, SPManagedClientDataType, SPConfigurationProfileDataTypeCompliance and security posture assessment
PeripheralsSPUSBDataType, SPThunderboltDataType, SPAudioDataType, SPDisplaysDataTypePeripheral management and security validation

Enterprise Collection Policies

Comprehensive Collection

# Collect all available system information
./sysinfo_manager.sh collect comprehensive json false

# Include sensitive information for detailed analysis
./sysinfo_manager.sh collect comprehensive json true

Security-Focused Collection

# Collect security-relevant information only
./sysinfo_manager.sh collect security_focused json false

# Generate security compliance report
./sysinfo_manager.sh compliance nist

Hardware Inventory

# Collect hardware inventory data
./sysinfo_manager.sh collect hardware_inventory json false

# Register device in enterprise inventory
./sysinfo_manager.sh inventory register production

System Health Monitoring

Health Analysis

# Perform standard health analysis
./sysinfo_manager.sh analyze_health standard

# Detailed health analysis with comprehensive metrics
./sysinfo_manager.sh analyze_health detailed

Continuous Monitoring

# Monitor system health every 10 minutes
./sysinfo_manager.sh monitor 600 warning

# Monitor system health every 5 minutes with critical threshold
./sysinfo_manager.sh monitor 300 critical

Enterprise Device Inventory

Inventory Management

# Register device in production inventory
./sysinfo_manager.sh inventory register production

# Update device information
./sysinfo_manager.sh inventory update production

# List all devices in inventory
./sysinfo_manager.sh inventory list production

# Remove device from inventory
./sysinfo_manager.sh inventory remove production

Compliance and Security Reporting

NIST Cybersecurity Framework

# Generate NIST compliance report
./sysinfo_manager.sh compliance nist

HIPAA Security Rule

# Generate HIPAA compliance report
./sysinfo_manager.sh compliance hipaa

Fleet Deployment Examples

Deploy to Development Fleet

Create a fleet file dev_fleet.txt:

dev-mac-01.company.com
dev-mac-02.company.com
dev-mac-03.company.com
# Deploy comprehensive system monitoring
./sysinfo_manager.sh deploy_fleet install dev_fleet.txt comprehensive

Deploy Security Monitoring

# Deploy security-focused monitoring to production fleet
./sysinfo_manager.sh deploy_fleet install prod_fleet.txt security_focused

Advanced Enterprise Features

Automated Data Collection

The system provides automated data collection capabilities:

  • Scheduled collection with customizable intervals
  • Policy-driven data gathering based on organizational requirements
  • Intelligent filtering to reduce data volume while maintaining completeness
  • Secure transmission of collected data to central repositories

System Health Analytics

Advanced health monitoring includes:

  • Performance metrics analysis and trending
  • Resource utilization monitoring and alerting
  • Security posture assessment and recommendations
  • Predictive maintenance based on system health indicators

Enterprise Integration

Integration capabilities include:

  • LDAP/Active Directory integration for user and device management
  • SIEM integration for security event correlation
  • Asset management system integration
  • Compliance framework alignment and reporting

Important Security Considerations

  • Data sensitivity requires appropriate handling and encryption
  • Access controls must be implemented for sensitive system information
  • Audit logging should track all system information access and collection
  • Network security must protect data transmission between devices
  • Compliance requirements vary by industry and geographic location

Performance and Scalability

The enterprise system is designed for:

  • Large-scale deployment across thousands of devices
  • Efficient data collection with minimal system impact
  • Scalable storage for historical data and trend analysis
  • High availability with redundancy and failover capabilities
  • Performance optimization for various hardware configurations

This comprehensive system transforms basic system information retrieval into an enterprise-grade device management and monitoring platform with advanced analytics, compliance reporting, and fleet-wide management capabilities.

Tutorial

Nuevas actualizaciones y mejoras para Macfleet.

Configurando un Runner de GitHub Actions en un Mac Mini (Apple Silicon)

Runner de GitHub Actions

GitHub Actions es una plataforma poderosa de CI/CD que te permite automatizar tus flujos de trabajo de desarrollo de software. Aunque GitHub ofrece runners hospedados, los runners auto-hospedados proporcionan mayor control y personalización para tu configuración de CI/CD. Este tutorial te guía a través de la configuración y conexión de un runner auto-hospedado en un Mac mini para ejecutar pipelines de macOS.

Prerrequisitos

Antes de comenzar, asegúrate de tener:

  • Un Mac mini (regístrate en Macfleet)
  • Un repositorio de GitHub con derechos de administrador
  • Un gestor de paquetes instalado (preferiblemente Homebrew)
  • Git instalado en tu sistema

Paso 1: Crear una Cuenta de Usuario Dedicada

Primero, crea una cuenta de usuario dedicada para el runner de GitHub Actions:

# Crear la cuenta de usuario 'gh-runner'
sudo dscl . -create /Users/gh-runner
sudo dscl . -create /Users/gh-runner UserShell /bin/bash
sudo dscl . -create /Users/gh-runner RealName "GitHub runner"
sudo dscl . -create /Users/gh-runner UniqueID "1001"
sudo dscl . -create /Users/gh-runner PrimaryGroupID 20
sudo dscl . -create /Users/gh-runner NFSHomeDirectory /Users/gh-runner

# Establecer la contraseña para el usuario
sudo dscl . -passwd /Users/gh-runner tu_contraseña

# Agregar 'gh-runner' al grupo 'admin'
sudo dscl . -append /Groups/admin GroupMembership gh-runner

Cambia a la nueva cuenta de usuario:

su gh-runner

Paso 2: Instalar Software Requerido

Instala Git y Rosetta 2 (si usas Apple Silicon):

# Instalar Git si no está ya instalado
brew install git

# Instalar Rosetta 2 para Macs Apple Silicon
softwareupdate --install-rosetta

Paso 3: Configurar el Runner de GitHub Actions

  1. Ve a tu repositorio de GitHub
  2. Navega a Configuración > Actions > Runners

Runner de GitHub Actions

  1. Haz clic en "New self-hosted runner" (https://github.com/<username>/<repository>/settings/actions/runners/new)
  2. Selecciona macOS como imagen del runner y ARM64 como arquitectura
  3. Sigue los comandos proporcionados para descargar y configurar el runner

Runner de GitHub Actions

Crea un archivo .env en el directorio _work del runner:

# archivo _work/.env
ImageOS=macos15
XCODE_15_DEVELOPER_DIR=/Applications/Xcode.app/Contents/Developer
  1. Ejecuta el script run.sh en tu directorio del runner para completar la configuración.
  2. Verifica que el runner esté activo y escuchando trabajos en la terminal y revisa la configuración del repositorio de GitHub para la asociación del runner y el estado Idle.

Runner de GitHub Actions

Paso 4: Configurar Sudoers (Opcional)

Si tus acciones requieren privilegios de root, configura el archivo sudoers:

sudo visudo

Agrega la siguiente línea:

gh-runner ALL=(ALL) NOPASSWD: ALL

Paso 5: Usar el Runner en Flujos de Trabajo

Configura tu flujo de trabajo de GitHub Actions para usar el runner auto-hospedado:

name: Flujo de trabajo de muestra

on:
  workflow_dispatch:

jobs:
  build:
    runs-on: [self-hosted, macOS, ARM64]
    steps:
      - name: Instalar NodeJS
        run: brew install node

El runner está autenticado en tu repositorio y etiquetado con self-hosted, macOS, y ARM64. Úsalo en tus flujos de trabajo especificando estas etiquetas en el campo runs-on:

runs-on: [self-hosted, macOS, ARM64]

Mejores Prácticas

  • Mantén tu software del runner actualizado
  • Monitorea regularmente los logs del runner para problemas
  • Usa etiquetas específicas para diferentes tipos de runners
  • Implementa medidas de seguridad apropiadas
  • Considera usar múltiples runners para balanceo de carga

Solución de Problemas

Problemas comunes y soluciones:

  1. Runner no conectando:

    • Verifica conectividad de red
    • Verifica validez del token de GitHub
    • Asegúrate de permisos apropiados
  2. Fallas de construcción:

    • Verifica instalación de Xcode
    • Verifica dependencias requeridas
    • Revisa logs del flujo de trabajo
  3. Problemas de permisos:

    • Verifica permisos de usuario
    • Verifica configuración de sudoers
    • Revisa permisos del sistema de archivos

Conclusión

Ahora tienes un runner auto-hospedado de GitHub Actions configurado en tu Mac mini. Esta configuración te proporciona más control sobre tu entorno de CI/CD y te permite ejecutar flujos de trabajo específicos de macOS de manera eficiente.

Recuerda mantener regularmente tu runner y mantenerlo actualizado con los últimos parches de seguridad y versiones de software.

Aplicación Nativa

Aplicación nativa de Macfleet

Guía de Instalación de Macfleet

Macfleet es una solución poderosa de gestión de flota diseñada específicamente para entornos de Mac Mini alojados en la nube. Como proveedor de hosting en la nube de Mac Mini, puedes usar Macfleet para monitorear, gestionar y optimizar toda tu flota de instancias Mac virtualizadas.

Esta guía de instalación te llevará a través de la configuración del monitoreo de Macfleet en sistemas macOS, Windows y Linux para asegurar una supervisión integral de tu infraestructura en la nube.

🍎 macOS

  • Descarga el archivo .dmg para Mac aquí
  • Haz doble clic en el archivo .dmg descargado
  • Arrastra la aplicación Macfleet a la carpeta Aplicaciones
  • Expulsa el archivo .dmg
  • Abre Preferencias del Sistema > Seguridad y Privacidad
    • Pestaña Privacidad > Accesibilidad
    • Marca Macfleet para permitir el monitoreo
  • Inicia Macfleet desde Aplicaciones
  • El seguimiento comienza automáticamente

🪟 Windows

  • Descarga el archivo .exe para Windows aquí
  • Haz clic derecho en el archivo .exe > "Ejecutar como administrador"
  • Sigue el asistente de instalación
  • Acepta los términos y condiciones
  • Permite en Windows Defender si se solicita
  • Concede permisos de monitoreo de aplicaciones
  • Inicia Macfleet desde el Menú Inicio
  • La aplicación comienza el seguimiento automáticamente

🐧 Linux

  • Descarga el paquete .deb (Ubuntu/Debian) o .rpm (CentOS/RHEL) aquí
  • Instala usando tu gestor de paquetes
    • Ubuntu/Debian: sudo dpkg -i Macfleet-linux.deb
    • CentOS/RHEL: sudo rpm -ivh Macfleet-linux.rpm
  • Permite permisos de acceso X11 si se solicita
  • Agrega el usuario a los grupos apropiados si es necesario
  • Inicia Macfleet desde el menú de Aplicaciones
  • La aplicación comienza el seguimiento automáticamente

Nota: Después de la instalación en todos los sistemas, inicia sesión con tus credenciales de Macfleet para sincronizar datos con tu panel de control.