Tutorial

Novas atualizações e melhorias para a Macfleet.

Aviso importante

Os exemplos de código e scripts fornecidos nestes tutoriais são apenas para fins educacionais. A Macfleet não é responsável por quaisquer problemas, danos ou vulnerabilidades de segurança que possam surgir do uso, modificação ou implementação destes exemplos. Sempre revise e teste o código em um ambiente seguro antes de usá-lo em sistemas de produção.

File Discovery and Search Management on macOS

Discover and manage files across your MacFleet devices using advanced file search and discovery systems. This tutorial covers file path finding, extension-based searches, content analysis, and comprehensive file lifecycle management.

Understanding macOS File Discovery

macOS provides several file discovery and search capabilities:

  • find - Command-line file and directory search utility
  • File Path Resolution - Locate specific files by name and extension
  • Extension Filtering - Search for files by file type and format
  • Content Search - Find files based on content and metadata
  • Spotlight Integration - Leverage macOS indexing for fast searches

Basic File Discovery Operations

Find File Path

#!/bin/bash

# Basic file path finding
find / -name 'file name with extension' -print 2>/dev/null

echo "File path search completed"

Enhanced File Discovery

#!/bin/bash

# Comprehensive file discovery with multiple search methods
discover_file_paths() {
    local file_pattern="$1"
    local search_scope="${2:-/}"
    local search_type="${3:-name}"
    
    echo "=== File Discovery and Path Resolution ==="
    echo "Search Pattern: $file_pattern"
    echo "Search Scope: $search_scope"
    echo "Search Type: $search_type"
    
    # Validate search parameters
    if [[ -z "$file_pattern" ]]; then
        echo "❌ File pattern is required"
        return 1
    fi
    
    if [[ ! -d "$search_scope" ]]; then
        echo "❌ Search scope directory not found: $search_scope"
        return 1
    fi
    
    # Perform search based on type
    echo "Starting file discovery..."
    local results_count=0
    
    case "$search_type" in
        "name")
            echo "Searching by filename..."
            find "$search_scope" -name "$file_pattern" -print 2>/dev/null | while read -r file_path; do
                echo "Found: $file_path"
                ((results_count++))
            done
            ;;
        "iname")
            echo "Searching by filename (case-insensitive)..."
            find "$search_scope" -iname "$file_pattern" -print 2>/dev/null | while read -r file_path; do
                echo "Found: $file_path"
                ((results_count++))
            done
            ;;
        "type")
            echo "Searching by file type..."
            find "$search_scope" -type f -name "$file_pattern" -print 2>/dev/null | while read -r file_path; do
                echo "Found: $file_path"
                ((results_count++))
            done
            ;;
        "content")
            echo "Searching by content..."
            grep -r "$file_pattern" "$search_scope" 2>/dev/null | while read -r match; do
                echo "Content match: $match"
                ((results_count++))
            done
            ;;
        *)
            echo "❌ Unknown search type: $search_type"
            return 1
            ;;
    esac
    
    echo "✅ File discovery completed"
    log_discovery_action "$file_pattern" "$search_scope" "$search_type" "success"
    
    return 0
}

# Example usage
# discover_file_paths "document.txt" "/" "name"

List Files by Extension

#!/bin/bash

# Enhanced file extension search
find_files_by_extension() {
    local extension="$1"
    local count="${2:-10}"
    local search_path="${3:-/}"
    
    echo "=== Files by Extension Search ==="
    echo "Extension: .$extension"
    echo "Result Limit: $count"
    echo "Search Path: $search_path"
    
    # Basic extension search
    echo "Searching for .$extension files..."
    find "$search_path" -name "*.$extension" -print 2>/dev/null | head -n "$count"
    
    echo "✅ Extension search completed"
}

# Example usage
# find_files_by_extension "txt" 10 "/"

File Discovery Categories

File Type Classifications

#!/bin/bash

# File discovery categories for different file types and purposes
declare -A FILE_CATEGORIES=(
    ["system_config"]="System configuration files and preferences"
    ["application_data"]="Application data files and user preferences"
    ["media_content"]="Images, videos, audio files and multimedia content"
    ["document_files"]="Text documents, spreadsheets, presentations"
    ["development_code"]="Source code, scripts, development projects"
    ["archive_compressed"]="Compressed archives and backup files"
    ["security_certificates"]="Security certificates, keys, and credentials"
    ["log_diagnostic"]="System logs, diagnostic files, and troubleshooting data"
    ["cache_temporary"]="Cache files, temporary data, and disposable content"
    ["database_structured"]="Database files and structured data storage"
)

# File extensions for each category
declare -A CATEGORY_EXTENSIONS=(
    ["system_config"]="plist,conf,cfg,ini,settings,preferences"
    ["application_data"]="app,dmg,pkg,bundle,framework"
    ["media_content"]="jpg,jpeg,png,gif,mp4,mov,mp3,wav,m4a"
    ["document_files"]="pdf,doc,docx,xls,xlsx,ppt,pptx,txt,rtf"
    ["development_code"]="swift,m,h,py,js,ts,php,java,cpp,c"
    ["archive_compressed"]="zip,tar,gz,bz2,rar,7z,dmg"
    ["security_certificates"]="p12,pem,crt,key,keychain,cer"
    ["log_diagnostic"]="log,crash,diag,report,trace"
    ["cache_temporary"]="cache,tmp,temp,bak,swp"
    ["database_structured"]="db,sqlite,sql,json,xml,csv"
)

# Search priorities for different categories
declare -A SEARCH_PRIORITIES=(
    ["system_config"]="high"
    ["application_data"]="medium"
    ["media_content"]="low"
    ["document_files"]="high"
    ["development_code"]="medium"
    ["archive_compressed"]="low"
    ["security_certificates"]="critical"
    ["log_diagnostic"]="medium"
    ["cache_temporary"]="low"
    ["database_structured"]="high"
)

print_file_categories() {
    echo "=== File Discovery Categories ==="
    for category in "${!FILE_CATEGORIES[@]}"; do
        echo "Category: $category"
        echo "  Description: ${FILE_CATEGORIES[$category]}"
        echo "  Extensions: ${CATEGORY_EXTENSIONS[$category]}"
        echo "  Priority: ${SEARCH_PRIORITIES[$category]}"
        echo ""
    done
}

# Display available categories
print_file_categories

File Discovery Policies

Search and Discovery Policies

#!/bin/bash

# File discovery policies for different organizational requirements
declare -A DISCOVERY_POLICIES=(
    ["security_audit"]="Security-focused file discovery with comprehensive scanning"
    ["compliance_gdpr"]="GDPR compliance file discovery for personal data identification"
    ["asset_inventory"]="Complete asset inventory and file cataloging"
    ["performance_cleanup"]="Performance optimization through file cleanup identification"
    ["backup_verification"]="Backup verification and data integrity checking"
    ["forensic_investigation"]="Forensic file discovery for incident investigation"
)

# Get discovery policy configuration
get_discovery_policy() {
    local policy_type="$1"
    
    case "$policy_type" in
        "security_audit")
            cat << EOF
{
    "discovery_enabled": true,
    "search_scope": "comprehensive",
    "file_types_priority": ["security_certificates", "system_config", "log_diagnostic"],
    "content_analysis": true,
    "metadata_collection": true,
    "permission_analysis": true,
    "hash_verification": true,
    "access_tracking": true,
    "encryption_detection": true,
    "suspicious_patterns": ["password", "key", "token", "secret"],
    "reporting_level": "detailed",
    "audit_logging": "comprehensive",
    "real_time_monitoring": true
}
EOF
            ;;
        "compliance_gdpr")
            cat << EOF
{
    "discovery_enabled": true,
    "search_scope": "user_data_focused",
    "file_types_priority": ["document_files", "database_structured", "application_data"],
    "content_analysis": true,
    "metadata_collection": true,
    "personal_data_detection": true,
    "data_classification": true,
    "retention_analysis": true,
    "consent_tracking": false,
    "data_subject_identification": true,
    "cross_border_analysis": true,
    "privacy_patterns": ["email", "phone", "ssn", "passport", "address"],
    "reporting_level": "privacy_compliant",
    "audit_logging": "gdpr_compliant",
    "data_mapping": true
}
EOF
            ;;
        "asset_inventory")
            cat << EOF
{
    "discovery_enabled": true,
    "search_scope": "complete_system",
    "file_types_priority": ["application_data", "system_config", "document_files"],
    "content_analysis": false,
    "metadata_collection": true,
    "size_analysis": true,
    "modification_tracking": true,
    "ownership_analysis": true,
    "version_detection": true,
    "license_compliance": true,
    "duplicate_detection": true,
    "storage_optimization": true,
    "reporting_level": "inventory_focused",
    "audit_logging": "standard",
    "cataloging": true
}
EOF
            ;;
        "forensic_investigation")
            cat << EOF
{
    "discovery_enabled": true,
    "search_scope": "forensic_complete",
    "file_types_priority": ["all_types"],
    "content_analysis": true,
    "metadata_collection": true,
    "timeline_analysis": true,
    "hash_verification": true,
    "signature_analysis": true,
    "deleted_file_recovery": true,
    "steganography_detection": true,
    "network_artifact_analysis": true,
    "chain_of_custody": true,
    "evidence_preservation": true,
    "reporting_level": "forensic_detailed",
    "audit_logging": "forensic_compliant",
    "legal_hold": true
}
EOF
            ;;
        *)
            echo "Unknown discovery policy: $policy_type"
            return 1
            ;;
    esac
}

# Apply discovery policy
apply_discovery_policy() {
    local policy="$1"
    local config_file="/tmp/discovery_policy.json"
    
    echo "Applying file discovery policy: $policy"
    
    get_discovery_policy "$policy" > "$config_file"
    
    if [[ ! -f "$config_file" ]]; then
        echo "❌ Failed to generate policy configuration"
        return 1
    fi
    
    echo "✅ File discovery policy applied successfully"
    echo "Configuration: $config_file"
    
    # Display key policy settings
    echo "=== Policy Summary ==="
    echo "Discovery Enabled: $(jq -r '.discovery_enabled' "$config_file")"
    echo "Search Scope: $(jq -r '.search_scope' "$config_file")"
    echo "Content Analysis: $(jq -r '.content_analysis' "$config_file")"
    echo "Metadata Collection: $(jq -r '.metadata_collection' "$config_file")"
    echo "Reporting Level: $(jq -r '.reporting_level' "$config_file")"
    
    return 0
}

Advanced File Discovery and Analysis

Comprehensive File Discovery System

#!/bin/bash

# Advanced file discovery with content analysis and metadata extraction
advanced_file_discovery() {
    local search_criteria="$1"
    local analysis_level="${2:-standard}"
    local output_format="${3:-text}"
    
    echo "=== Advanced File Discovery System ==="
    echo "Search Criteria: $search_criteria"
    echo "Analysis Level: $analysis_level"
    echo "Output Format: $output_format"
    
    local discovery_report="/tmp/file_discovery_$(date +%Y%m%d_%H%M%S).json"
    
    # Initialize discovery report
    cat > "$discovery_report" << EOF
{
    "discovery_session": {
        "search_criteria": "$search_criteria",
        "analysis_level": "$analysis_level",
        "timestamp": "$(date -Iseconds)",
        "hostname": "$(hostname)",
        "operator": "$(whoami)"
    },
    "discovered_files": [],
    "file_statistics": {},
    "content_analysis": {},
    "security_findings": {}
}
EOF
    
    # Perform comprehensive file discovery
    echo "Performing comprehensive file search..."
    
    # Search by multiple criteria
    local files_found=0
    
    # Basic filename search
    echo "  - Searching by filename patterns..."
    find / -name "*$search_criteria*" -type f -print 2>/dev/null | while read -r file_path; do
        analyze_discovered_file "$file_path" "$analysis_level" "$discovery_report"
        ((files_found++))
    done
    
    # Content-based search
    if [[ "$analysis_level" == "comprehensive" ]]; then
        echo "  - Performing content analysis..."
        grep -r "$search_criteria" / 2>/dev/null | head -100 | while read -r match; do
            local file_path
            file_path=$(echo "$match" | cut -d':' -f1)
            analyze_discovered_file "$file_path" "$analysis_level" "$discovery_report"
        done
    fi
    
    # Generate file statistics
    generate_file_statistics "$discovery_report"
    
    # Display results
    echo ""
    echo "Discovery Results:"
    echo "  Files Found: $files_found"
    echo "  Discovery Report: $discovery_report"
    
    # Format output
    case "$output_format" in
        "json")
            cat "$discovery_report"
            ;;
        "summary")
            jq -r '.discovery_session, .file_statistics' "$discovery_report"
            ;;
        *)
            echo "Discovery completed - see report file for details"
            ;;
    esac
    
    return 0
}

# Analyze discovered file
analyze_discovered_file() {
    local file_path="$1"
    local analysis_level="$2"
    local report_file="$3"
    
    if [[ ! -f "$file_path" ]]; then
        return 1
    fi
    
    # Basic file information
    local file_size
    file_size=$(stat -f%z "$file_path" 2>/dev/null || echo "0")
    local file_permissions
    file_permissions=$(stat -f%A "$file_path" 2>/dev/null || echo "unknown")
    local file_owner
    file_owner=$(stat -f%Su "$file_path" 2>/dev/null || echo "unknown")
    local modification_time
    modification_time=$(stat -f%Sm "$file_path" 2>/dev/null || echo "unknown")
    
    # Enhanced analysis for comprehensive level
    local file_type="unknown"
    local content_preview=""
    local security_flags=""
    
    if [[ "$analysis_level" == "comprehensive" ]]; then
        file_type=$(file -b "$file_path" 2>/dev/null || echo "unknown")
        
        # Safe content preview for text files
        if file "$file_path" | grep -q "text"; then
            content_preview=$(head -c 200 "$file_path" 2>/dev/null | tr '\n' ' ')
        fi
        
        # Security analysis
        if [[ "$file_permissions" =~ 7.* ]]; then
            security_flags="executable_by_owner"
        fi
        
        if [[ "$file_path" =~ \.key$|\.pem$|\.p12$ ]]; then
            security_flags="${security_flags},potential_security_credential"
        fi
    fi
    
    # Log file discovery
    log_discovered_file "$file_path" "$file_size" "$file_type" "$security_flags"
}

# Generate file statistics
generate_file_statistics() {
    local report_file="$1"
    
    # Calculate basic statistics
    local total_files_found=0
    local total_size=0
    local file_types=()
    
    # Update report with statistics
    jq --argjson total_files "$total_files_found" \
       --argjson total_size "$total_size" \
       '.file_statistics = {
          "total_files_found": $total_files,
          "total_size_bytes": $total_size,
          "analysis_timestamp": "'$(date -Iseconds)'"
        }' "$report_file" > "${report_file}.tmp" && mv "${report_file}.tmp" "$report_file"
}

# Log discovered file
log_discovered_file() {
    local file_path="$1"
    local file_size="$2"
    local file_type="$3"
    local security_flags="$4"
    
    echo "$(date '+%Y-%m-%d %H:%M:%S') - File Discovered: $file_path (Size: $file_size, Type: $file_type, Security: $security_flags)" >> "/var/log/macfleet_file_discovery.log"
}

File Discovery Management System

#!/bin/bash

# MacFleet File Discovery and Search Management System
# Comprehensive file discovery, cataloging, and management

# Configuration
CONFIG_DIR="/etc/macfleet/discovery"
LOG_FILE="/var/log/macfleet_file_discovery.log"
DATA_DIR="/var/data/macfleet/discovery"
REPORTS_DIR="/var/reports/macfleet/discovery"
AUDIT_LOG="/var/log/macfleet_discovery_audit.log"
INDEX_DIR="/var/index/macfleet/discovery"

# Create required directories
create_directories() {
    local directories=("$CONFIG_DIR" "$DATA_DIR" "$REPORTS_DIR" "$INDEX_DIR")
    
    for dir in "${directories[@]}"; do
        if [[ ! -d "$dir" ]]; then
            sudo mkdir -p "$dir"
            sudo chmod 755 "$dir"
        fi
    done
}

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

log_error() {
    echo "$(date '+%Y-%m-%d %H:%M:%S') [ERROR] $1" | tee -a "$LOG_FILE" >&2
}

audit_log() {
    echo "$(date '+%Y-%m-%d %H:%M:%S') [AUDIT] $1" | tee -a "$AUDIT_LOG"
}

# File system indexing
create_file_index() {
    local index_scope="${1:-/Users}"
    local index_level="${2:-standard}"
    
    log_action "Creating file system index: $index_scope (Level: $index_level)"
    
    echo "=== File System Indexing ==="
    echo "Index Scope: $index_scope"
    echo "Index Level: $index_level"
    
    local index_file="$INDEX_DIR/file_index_$(date +%Y%m%d_%H%M%S).json"
    
    # Initialize index
    cat > "$index_file" << EOF
{
    "index_metadata": {
        "scope": "$index_scope",
        "level": "$index_level",
        "created": "$(date -Iseconds)",
        "hostname": "$(hostname)",
        "total_files": 0,
        "total_size": 0
    },
    "file_entries": []
}
EOF
    
    echo "Starting file system indexing..."
    local file_count=0
    local total_size=0
    
    # Index files based on level
    case "$index_level" in
        "basic")
            find "$index_scope" -type f -print 2>/dev/null | while read -r file_path; do
                index_file_basic "$file_path" "$index_file"
                ((file_count++))
                
                if [[ $((file_count % 1000)) -eq 0 ]]; then
                    echo "  Indexed $file_count files..."
                fi
            done
            ;;
        "standard")
            find "$index_scope" -type f -print 2>/dev/null | while read -r file_path; do
                index_file_standard "$file_path" "$index_file"
                ((file_count++))
                
                if [[ $((file_count % 500)) -eq 0 ]]; then
                    echo "  Indexed $file_count files..."
                fi
            done
            ;;
        "comprehensive")
            find "$index_scope" -type f -print 2>/dev/null | while read -r file_path; do
                index_file_comprehensive "$file_path" "$index_file"
                ((file_count++))
                
                if [[ $((file_count % 100)) -eq 0 ]]; then
                    echo "  Indexed $file_count files..."
                fi
            done
            ;;
        *)
            echo "❌ Unknown index level: $index_level"
            return 1
            ;;
    esac
    
    echo "✅ File system indexing completed"
    echo "  Files Indexed: $file_count"
    echo "  Index File: $index_file"
    
    audit_log "File system index created: $index_scope ($file_count files)"
    
    return 0
}

# Index file with basic information
index_file_basic() {
    local file_path="$1"
    local index_file="$2"
    
    if [[ ! -f "$file_path" ]]; then
        return 1
    fi
    
    local file_size
    file_size=$(stat -f%z "$file_path" 2>/dev/null || echo "0")
    local modification_time
    modification_time=$(stat -f%Sm "$file_path" 2>/dev/null || echo "unknown")
    
    # Basic indexing (minimal overhead)
    echo "Indexed: $file_path" >> "${index_file}.basic_log"
}

# Index file with standard information
index_file_standard() {
    local file_path="$1"
    local index_file="$2"
    
    if [[ ! -f "$file_path" ]]; then
        return 1
    fi
    
    local file_size
    file_size=$(stat -f%z "$file_path" 2>/dev/null || echo "0")
    local file_permissions
    file_permissions=$(stat -f%A "$file_path" 2>/dev/null || echo "unknown")
    local file_owner
    file_owner=$(stat -f%Su "$file_path" 2>/dev/null || echo "unknown")
    local file_extension
    file_extension="${file_path##*.}"
    
    # Standard indexing with metadata
    echo "$(date -Iseconds),$file_path,$file_size,$file_permissions,$file_owner,$file_extension" >> "${index_file}.csv"
}

# Index file with comprehensive information
index_file_comprehensive() {
    local file_path="$1"
    local index_file="$2"
    
    if [[ ! -f "$file_path" ]]; then
        return 1
    fi
    
    # Comprehensive file analysis
    local file_info
    file_info=$(analyze_file_comprehensive "$file_path")
    
    # Store in detailed format
    echo "$file_info" >> "${index_file}.detailed_log"
}

# Comprehensive file analysis
analyze_file_comprehensive() {
    local file_path="$1"
    
    # Gather all available file information
    local file_size
    file_size=$(stat -f%z "$file_path" 2>/dev/null || echo "0")
    local file_type
    file_type=$(file -b "$file_path" 2>/dev/null || echo "unknown")
    local file_hash
    file_hash=$(shasum -a 256 "$file_path" 2>/dev/null | cut -d' ' -f1 || echo "unknown")
    
    echo "Path:$file_path|Size:$file_size|Type:$file_type|Hash:$file_hash|Timestamp:$(date -Iseconds)"
}

# Search indexed files
search_file_index() {
    local search_term="$1"
    local search_type="${2:-name}"
    local index_scope="${3:-latest}"
    
    log_action "Searching file index: $search_term (Type: $search_type)"
    
    echo "=== Indexed File Search ==="
    echo "Search Term: $search_term"
    echo "Search Type: $search_type"
    echo "Index Scope: $index_scope"
    
    # Find the appropriate index file
    local index_file
    if [[ "$index_scope" == "latest" ]]; then
        index_file=$(ls -t "$INDEX_DIR"/file_index_*.json 2>/dev/null | head -1)
    else
        index_file="$INDEX_DIR/$index_scope"
    fi
    
    if [[ ! -f "$index_file" ]]; then
        echo "❌ No index file found"
        return 1
    fi
    
    echo "Using index: $index_file"
    
    # Perform search based on type
    case "$search_type" in
        "name")
            grep -i "$search_term" "${index_file}.csv" 2>/dev/null | head -20
            ;;
        "extension")
            grep ",$search_term$" "${index_file}.csv" 2>/dev/null | head -20
            ;;
        "size")
            # Search by file size range
            echo "Size-based search not implemented in basic version"
            ;;
        *)
            echo "❌ Unknown search type: $search_type"
            return 1
            ;;
    esac
    
    audit_log "Index search completed: $search_term ($search_type)"
    
    return 0
}

# Generate discovery report
generate_discovery_report() {
    local report_type="$1"
    local scope="${2:-system}"
    
    log_action "Generating discovery report: $report_type (Scope: $scope)"
    
    echo "=== File Discovery Report Generation ==="
    echo "Report Type: $report_type"
    echo "Scope: $scope"
    
    local report_file="$REPORTS_DIR/discovery_report_${report_type}_$(date +%Y%m%d_%H%M%S).json"
    
    case "$report_type" in
        "summary")
            generate_summary_report "$scope" "$report_file"
            ;;
        "detailed")
            generate_detailed_report "$scope" "$report_file"
            ;;
        "security")
            generate_security_report "$scope" "$report_file"
            ;;
        "compliance")
            generate_compliance_report "$scope" "$report_file"
            ;;
        *)
            echo "❌ Unknown report type: $report_type"
            return 1
            ;;
    esac
    
    echo "✅ Discovery report generated: $report_file"
    audit_log "Discovery report generated: $report_type for $scope"
    
    return 0
}

# Generate summary report
generate_summary_report() {
    local scope="$1"
    local report_file="$2"
    
    # Collect basic statistics
    local total_files
    total_files=$(find "$scope" -type f 2>/dev/null | wc -l | tr -d ' ')
    local total_directories
    total_directories=$(find "$scope" -type d 2>/dev/null | wc -l | tr -d ' ')
    
    cat > "$report_file" << EOF
{
    "report_type": "summary",
    "scope": "$scope",
    "generated": "$(date -Iseconds)",
    "hostname": "$(hostname)",
    "statistics": {
        "total_files": $total_files,
        "total_directories": $total_directories
    }
}
EOF
}

# Main function with command routing
main() {
    local command="$1"
    shift
    
    # Initialize
    create_directories
    
    case "$command" in
        "find_file")
            # Find specific file by name
            discover_file_paths "$@"
            ;;
        "find_extension")
            # Find files by extension
            find_files_by_extension "$@"
            ;;
        "advanced_search")
            # Advanced file discovery
            advanced_file_discovery "$@"
            ;;
        "create_index")
            # Create file system index
            create_file_index "$@"
            ;;
        "search_index")
            # Search existing index
            search_file_index "$@"
            ;;
        "apply_policy")
            # Apply discovery policy
            apply_discovery_policy "$@"
            ;;
        "generate_report")
            # Generate discovery report
            generate_discovery_report "$@"
            ;;
        "show_categories")
            # Show file categories
            print_file_categories
            ;;
        "show_policies")
            # Show available policies
            for policy in security_audit compliance_gdpr asset_inventory performance_cleanup backup_verification forensic_investigation; do
                echo "Policy: $policy"
                get_discovery_policy "$policy" | jq .
                echo ""
            done
            ;;
        *)
            echo "MacFleet File Discovery and Search Management System"
            echo "Usage: $0 <command> [options]"
            echo ""
            echo "Commands:"
            echo "  find_file <pattern> [scope] [type]                - Find specific files by pattern"
            echo "  find_extension <ext> [count] [path]               - Find files by extension"
            echo "  advanced_search <criteria> [level] [format]      - Advanced file discovery"
            echo "  create_index [scope] [level]                     - Create file system index"
            echo "  search_index <term> [type] [scope]               - Search existing index"
            echo "  apply_policy <policy>                            - Apply discovery policy"
            echo "  generate_report <type> [scope]                   - Generate discovery report"
            echo "  show_categories                                  - Show file categories"
            echo "  show_policies                                    - Show discovery policies"
            echo ""
            echo "Examples:"
            echo "  $0 find_file \"document.txt\" \"/Users\" \"name\""
            echo "  $0 find_extension \"pdf\" 20 \"/Users\""
            echo "  $0 advanced_search \"config\" \"comprehensive\" \"json\""
            echo "  $0 create_index \"/Users\" \"standard\""
            echo "  $0 search_index \"report\" \"name\" \"latest\""
            echo "  $0 apply_policy \"security_audit\""
            echo "  $0 generate_report \"summary\" \"/Users\""
            ;;
    esac
}

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

Security Considerations

File Discovery Security

  • Access Controls - Respect file permissions and access restrictions
  • Sensitive Data Protection - Avoid exposing sensitive file contents in logs
  • Performance Impact - Monitor system performance during large-scale discovery
  • Privacy Compliance - Ensure discovery practices comply with privacy regulations
  • Audit Trails - Maintain comprehensive logs of discovery activities

Compliance Framework

  • Data Classification - Properly classify discovered files based on sensitivity
  • Retention Policies - Implement appropriate data retention and disposal
  • Access Logging - Log all file access and discovery activities
  • Privacy Protection - Protect personal and sensitive information during discovery
  • Regulatory Compliance - Meet industry-specific discovery and cataloging requirements

Troubleshooting Guide

Common Issues

Permission Denied Errors

  • Run discovery with appropriate privileges: sudo for system-wide searches
  • Check file and directory permissions: ls -la
  • Verify search scope accessibility

Slow Search Performance

  • Limit search scope to specific directories
  • Use indexed searches for frequently accessed data
  • Consider search criteria specificity

Too Many Results

  • Use more specific search patterns
  • Implement result limits with head -n <count>
  • Filter by file type or date ranges

Diagnostic Commands

# Test basic find functionality
find /Users -name "*.txt" -print 2>/dev/null | head -5

# Check file system permissions
ls -la /path/to/search/directory

# Monitor search performance
time find /Users -name "pattern" -print 2>/dev/null

# Check available disk space for indexing
df -h

Important Notes

  • File Path Escaping - Use quotes or backslashes for paths with spaces: "New Folder/file.txt" or New\ Folder/file.txt
  • Search Scope - Broader searches take longer but provide more complete results
  • System Impact - Large-scale file discovery can impact system performance
  • Result Limits - Use appropriate limits to prevent overwhelming output
  • Index Maintenance - Regularly update file indexes for accuracy
  • Security Awareness - Be cautious when searching for sensitive files and credentials

Tutorial

Novas atualizações e melhorias para a Macfleet.

Configurando um Runner do GitHub Actions em um Mac Mini (Apple Silicon)

Runner do GitHub Actions

GitHub Actions é uma plataforma poderosa de CI/CD que permite automatizar seus fluxos de trabalho de desenvolvimento de software. Embora o GitHub ofereça runners hospedados, runners auto-hospedados fornecem maior controle e personalização para sua configuração de CI/CD. Este tutorial o guia através da configuração e conexão de um runner auto-hospedado em um Mac mini para executar pipelines do macOS.

Pré-requisitos

Antes de começar, certifique-se de ter:

  • Um Mac mini (registre-se no Macfleet)
  • Um repositório GitHub com direitos de administrador
  • Um gerenciador de pacotes instalado (preferencialmente Homebrew)
  • Git instalado em seu sistema

Passo 1: Criar uma Conta de Usuário Dedicada

Primeiro, crie uma conta de usuário dedicada para o runner do GitHub Actions:

# Criar a conta de usuário '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

# Definir a senha para o usuário
sudo dscl . -passwd /Users/gh-runner sua_senha

# Adicionar 'gh-runner' ao grupo 'admin'
sudo dscl . -append /Groups/admin GroupMembership gh-runner

Mude para a nova conta de usuário:

su gh-runner

Passo 2: Instalar Software Necessário

Instale Git e Rosetta 2 (se estiver usando Apple Silicon):

# Instalar Git se ainda não estiver instalado
brew install git

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

Passo 3: Configurar o Runner do GitHub Actions

  1. Vá para seu repositório GitHub
  2. Navegue para Configurações > Actions > Runners

Runner do GitHub Actions

  1. Clique em "New self-hosted runner" (https://github.com/<username>/<repository>/settings/actions/runners/new)
  2. Selecione macOS como imagem do runner e ARM64 como arquitetura
  3. Siga os comandos fornecidos para baixar e configurar o runner

Runner do GitHub Actions

Crie um arquivo .env no diretório _work do runner:

# arquivo _work/.env
ImageOS=macos15
XCODE_15_DEVELOPER_DIR=/Applications/Xcode.app/Contents/Developer
  1. Execute o script run.sh em seu diretório do runner para completar a configuração.
  2. Verifique se o runner está ativo e ouvindo por trabalhos no terminal e verifique as configurações do repositório GitHub para a associação do runner e status Idle.

Runner do GitHub Actions

Passo 4: Configurar Sudoers (Opcional)

Se suas ações requerem privilégios de root, configure o arquivo sudoers:

sudo visudo

Adicione a seguinte linha:

gh-runner ALL=(ALL) NOPASSWD: ALL

Passo 5: Usar o Runner em Fluxos de Trabalho

Configure seu fluxo de trabalho do GitHub Actions para usar o runner auto-hospedado:

name: Fluxo de trabalho de exemplo

on:
  workflow_dispatch:

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

O runner está autenticado em seu repositório e rotulado com self-hosted, macOS, e ARM64. Use-o em seus fluxos de trabalho especificando estes rótulos no campo runs-on:

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

Melhores Práticas

  • Mantenha seu software do runner atualizado
  • Monitore regularmente os logs do runner para problemas
  • Use rótulos específicos para diferentes tipos de runners
  • Implemente medidas de segurança adequadas
  • Considere usar múltiplos runners para balanceamento de carga

Solução de Problemas

Problemas comuns e soluções:

  1. Runner não conectando:

    • Verifique conectividade de rede
    • Verifique validade do token GitHub
    • Certifique-se de permissões adequadas
  2. Falhas de build:

    • Verifique instalação do Xcode
    • Verifique dependências necessárias
    • Revise logs do fluxo de trabalho
  3. Problemas de permissão:

    • Verifique permissões do usuário
    • Verifique configuração sudoers
    • Revise permissões do sistema de arquivos

Conclusão

Agora você tem um runner auto-hospedado do GitHub Actions configurado em seu Mac mini. Esta configuração fornece mais controle sobre seu ambiente CI/CD e permite executar fluxos de trabalho específicos do macOS de forma eficiente.

Lembre-se de manter regularmente seu runner e mantê-lo atualizado com os patches de segurança e versões de software mais recentes.

Aplicativo Nativo

Aplicativo nativo do Macfleet

Guia de Instalação do Macfleet

Macfleet é uma solução poderosa de gerenciamento de frota projetada especificamente para ambientes Mac Mini hospedados na nuvem. Como provedor de hospedagem na nuvem Mac Mini, você pode usar o Macfleet para monitorar, gerenciar e otimizar toda sua frota de instâncias Mac virtualizadas.

Este guia de instalação o conduzirá através da configuração do monitoramento do Macfleet em sistemas macOS, Windows e Linux para garantir supervisão abrangente de sua infraestrutura na nuvem.

🍎 macOS

  • Baixe o arquivo .dmg para Mac aqui
  • Clique duas vezes no arquivo .dmg baixado
  • Arraste o aplicativo Macfleet para a pasta Aplicativos
  • Ejete o arquivo .dmg
  • Abra Preferências do Sistema > Segurança e Privacidade
    • Aba Privacidade > Acessibilidade
    • Marque Macfleet para permitir monitoramento
  • Inicie o Macfleet a partir de Aplicativos
  • O rastreamento inicia automaticamente

🪟 Windows

  • Baixe o arquivo .exe para Windows aqui
  • Clique com o botão direito no arquivo .exe > "Executar como administrador"
  • Siga o assistente de instalação
  • Aceite os termos e condições
  • Permita no Windows Defender se solicitado
  • Conceda permissões de monitoramento de aplicativo
  • Inicie o Macfleet a partir do Menu Iniciar
  • O aplicativo começa o rastreamento automaticamente

🐧 Linux

  • Baixe o pacote .deb (Ubuntu/Debian) ou .rpm (CentOS/RHEL) aqui
  • Instale usando seu gerenciador de pacotes
    • Ubuntu/Debian: sudo dpkg -i Macfleet-linux.deb
    • CentOS/RHEL: sudo rpm -ivh Macfleet-linux.rpm
  • Permita permissões de acesso X11 se solicitado
  • Adicione o usuário aos grupos apropriados se necessário
  • Inicie o Macfleet a partir do menu Aplicativos
  • O aplicativo começa o rastreamento automaticamente

Nota: Após a instalação em todos os sistemas, faça login com suas credenciais do Macfleet para sincronizar dados com seu painel de controle.