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.

User Details Management on macOS

Efficiently retrieve and manage user information across your MacFleet deployment with enterprise-grade user profiling, comprehensive audit capabilities, and detailed security controls. This tutorial transforms basic dscl commands into robust user management solutions.

Understanding Enterprise User Information Management

Enterprise user details management requires more than basic directory service queries, demanding:

  • Comprehensive user profiling with detailed attribute collection
  • Security classification of user accounts and privileges
  • Audit logging for compliance and security monitoring
  • Privacy protection for sensitive user information
  • Role-based access control for information retrieval
  • Integration capabilities with enterprise directory services

Core User Information Operations

Basic User Listing Commands

# List all users
dscl . list /Users

# List users with UniqueIDs
dscl . list /Users UniqueID

These utilize the directory service command-line utility (dscl) to retrieve user directory information.

Enterprise User Details Management System

#!/bin/bash

# MacFleet Enterprise User Details Management System
# Comprehensive user information retrieval with enterprise controls

# Configuration
SCRIPT_NAME="MacFleet User Details Manager"
VERSION="1.0.0"
LOG_FILE="/var/log/macfleet_user_details.log"
AUDIT_LOG="/var/log/macfleet_user_audit.log"
REPORT_DIR="/var/reports/macfleet"
TEMP_DIR="/tmp/macfleet_users"
PRIVACY_MODE=true
AUDIT_ALL_QUERIES=true
SYSTEM_UID_THRESHOLD=500
PRIVILEGED_GROUPS=("admin" "wheel" "_developer" "staff")
SENSITIVE_ATTRIBUTES=("Password" "ShadowHashData" "JPEGPhoto")

# Create necessary directories
mkdir -p "$TEMP_DIR"
mkdir -p "$REPORT_DIR"
mkdir -p "$(dirname "$LOG_FILE")"
mkdir -p "$(dirname "$AUDIT_LOG")"

# Set secure permissions
chmod 700 "$TEMP_DIR"
chmod 750 "$REPORT_DIR"

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

log_audit_query() {
    local query_type="$1"
    local target_user="$2"
    local requested_by="$3"
    local attributes="$4"
    
    if [[ "$AUDIT_ALL_QUERIES" == "true" ]]; then
        local timestamp=$(date '+%Y-%m-%d %H:%M:%S')
        local source_ip=$(who am i | awk '{print $5}' | tr -d '()')
        echo "QUERY|$timestamp|$query_type|$target_user|$requested_by|$source_ip|$attributes" >> "$AUDIT_LOG"
    fi
}

# Get comprehensive user information
get_user_details() {
    local username="$1"
    local privacy_filter="${2:-true}"
    local requested_by=$(whoami)
    
    log_audit_query "USER_DETAILS" "$username" "$requested_by" "full_profile"
    
    if ! dscl . -read "/Users/$username" &>/dev/null; then
        log_operation "ERROR" "User not found: $username"
        return 1
    fi
    
    echo "=== User Details: $username ==="
    echo "Query Time: $(date)"
    echo "Requested by: $requested_by"
    echo ""
    
    # Basic Information
    echo "== Basic Information =="
    local real_name=$(dscl . -read "/Users/$username" RealName 2>/dev/null | sed 's/RealName: //')
    local uid=$(dscl . -read "/Users/$username" UniqueID 2>/dev/null | awk '{print $2}')
    local gid=$(dscl . -read "/Users/$username" PrimaryGroupID 2>/dev/null | awk '{print $2}')
    local home_dir=$(dscl . -read "/Users/$username" NFSHomeDirectory 2>/dev/null | awk '{print $2}')
    local shell=$(dscl . -read "/Users/$username" UserShell 2>/dev/null | awk '{print $2}')
    
    echo "Username: $username"
    echo "Real Name: ${real_name:-N/A}"
    echo "User ID (UID): ${uid:-N/A}"
    echo "Primary Group ID (GID): ${gid:-N/A}"
    echo "Home Directory: ${home_dir:-N/A}"
    echo "Login Shell: ${shell:-N/A}"
    
    # Account Classification
    echo ""
    echo "== Account Classification =="
    if [[ $uid -lt $SYSTEM_UID_THRESHOLD ]]; then
        echo "Account Type: System Account"
        echo "Security Level: Critical"
    else
        echo "Account Type: User Account"
        echo "Security Level: Standard"
    fi
    
    # Group Memberships
    echo ""
    echo "== Group Memberships =="
    local groups=$(groups "$username" 2>/dev/null | cut -d: -f2 | xargs)
    echo "Groups: ${groups:-None}"
    
    # Check for privileged groups
    echo "Privileged Groups:"
    for group in "${PRIVILEGED_GROUPS[@]}"; do
        if echo "$groups" | grep -q "\b$group\b"; then
            echo "  ✓ $group"
        fi
    done
    
    # Account Status
    echo ""
    echo "== Account Status =="
    local account_policy=$(dscl . -read "/Users/$username" accountPolicyData 2>/dev/null)
    if [[ -n "$account_policy" ]]; then
        echo "Account Policy: Active"
        echo "$account_policy" | grep -E "(isDisabled|newPasswordRequired|passwordLastSetTime)"
    else
        echo "Account Policy: None"
    fi
    
    # Last Login Information
    echo ""
    echo "== Login Information =="
    local last_login=$(last -1 "$username" 2>/dev/null | head -1)
    if [[ -n "$last_login" && ! "$last_login" =~ "wtmp begins" ]]; then
        echo "Last Login: $last_login"
    else
        echo "Last Login: No login records found"
    fi
    
    # Home Directory Analysis
    echo ""
    echo "== Home Directory Analysis =="
    if [[ -d "$home_dir" ]]; then
        local dir_size=$(du -sh "$home_dir" 2>/dev/null | cut -f1)
        local dir_perms=$(ls -ld "$home_dir" 2>/dev/null | cut -d' ' -f1)
        local dir_owner=$(ls -ld "$home_dir" 2>/dev/null | awk '{print $3":"$4}')
        
        echo "Directory Exists: Yes"
        echo "Directory Size: ${dir_size:-Unknown}"
        echo "Permissions: ${dir_perms:-Unknown}"
        echo "Owner: ${dir_owner:-Unknown}"
    else
        echo "Directory Exists: No"
    fi
    
    # Privacy-filtered attributes
    if [[ "$privacy_filter" != "true" ]] && [[ "$requested_by" == "root" ]]; then
        echo ""
        echo "== Extended Attributes (Privileged) =="
        dscl . -read "/Users/$username" | grep -v -E "$(IFS=\|; echo "${SENSITIVE_ATTRIBUTES[*]}")"
    fi
    
    log_operation "INFO" "User details retrieved for: $username by $requested_by"
}

# List all users with classification
list_users_classified() {
    local include_system="${1:-false}"
    local format="${2:-table}"
    local requested_by=$(whoami)
    
    log_audit_query "LIST_USERS" "all" "$requested_by" "classified_list"
    
    echo "=== MacFleet User Classification Report ==="
    echo "Generated: $(date)"
    echo "Requested by: $requested_by"
    echo ""
    
    case "$format" in
        "table")
            printf "%-20s %-10s %-15s %-20s %-15s\n" "USERNAME" "UID" "TYPE" "REAL_NAME" "LAST_LOGIN"
            printf "%-20s %-10s %-15s %-20s %-15s\n" "--------" "---" "----" "---------" "----------"
            ;;
        "csv")
            echo "USERNAME,UID,TYPE,REAL_NAME,GROUPS,LAST_LOGIN,HOME_EXISTS"
            ;;
    esac
    
    # Get all users
    local users=($(dscl . list /Users | grep -v '^_'))
    
    for username in "${users[@]}"; do
        local uid=$(dscl . -read "/Users/$username" UniqueID 2>/dev/null | awk '{print $2}')
        
        # Skip system users if not requested
        if [[ "$include_system" == "false" && $uid -lt $SYSTEM_UID_THRESHOLD ]]; then
            continue
        fi
        
        local real_name=$(dscl . -read "/Users/$username" RealName 2>/dev/null | sed 's/RealName: //' | tr -d '\n')
        local home_dir=$(dscl . -read "/Users/$username" NFSHomeDirectory 2>/dev/null | awk '{print $2}')
        local groups=$(groups "$username" 2>/dev/null | cut -d: -f2 | xargs | tr ' ' ',')
        
        # Determine account type
        local account_type
        if [[ $uid -lt $SYSTEM_UID_THRESHOLD ]]; then
            account_type="System"
        else
            account_type="User"
        fi
        
        # Check for admin privileges
        if echo "$groups" | grep -q "admin"; then
            account_type="${account_type}/Admin"
        fi
        
        # Get last login
        local last_login=$(last -1 "$username" 2>/dev/null | head -1 | awk '{print $4" "$5" "$6}')
        if [[ "$last_login" =~ "wtmp begins" ]] || [[ -z "$last_login" ]]; then
            last_login="Never"
        fi
        
        # Home directory exists check
        local home_exists="No"
        if [[ -d "$home_dir" ]]; then
            home_exists="Yes"
        fi
        
        # Output in requested format
        case "$format" in
            "table")
                printf "%-20s %-10s %-15s %-20s %-15s\n" \
                    "$username" "$uid" "$account_type" "${real_name:0:19}" "${last_login:0:14}"
                ;;
            "csv")
                echo "$username,$uid,$account_type,\"$real_name\",\"$groups\",$last_login,$home_exists"
                ;;
        esac
    done
    
    echo ""
    echo "Total users found: ${#users[@]}"
    
    log_operation "INFO" "User list generated by $requested_by (format: $format, include_system: $include_system)"
}

# Analyze user privileges and security
analyze_user_security() {
    local username="$1"
    local requested_by=$(whoami)
    
    log_audit_query "SECURITY_ANALYSIS" "$username" "$requested_by" "privileges_audit"
    
    echo "=== Security Analysis: $username ==="
    echo "Analysis Time: $(date)"
    echo "Analyzed by: $requested_by"
    echo ""
    
    # Basic user validation
    if ! dscl . -read "/Users/$username" &>/dev/null; then
        log_operation "ERROR" "User not found for security analysis: $username"
        return 1
    fi
    
    local uid=$(dscl . -read "/Users/$username" UniqueID 2>/dev/null | awk '{print $2}')
    local groups=$(groups "$username" 2>/dev/null | cut -d: -f2)
    
    # Security Risk Assessment
    echo "== Security Risk Assessment =="
    local risk_level="LOW"
    local risk_factors=()
    
    # Check for administrative privileges
    if echo "$groups" | grep -q "admin"; then
        risk_level="HIGH"
        risk_factors+=("Administrative privileges")
    fi
    
    # Check for wheel group membership
    if echo "$groups" | grep -q "wheel"; then
        risk_level="CRITICAL"
        risk_factors+=("Wheel group membership (sudo access)")
    fi
    
    # Check for developer access
    if echo "$groups" | grep -q "_developer"; then
        risk_level="MEDIUM"
        risk_factors+=("Developer group membership")
    fi
    
    # Check for system account
    if [[ $uid -lt $SYSTEM_UID_THRESHOLD ]]; then
        risk_level="CRITICAL"
        risk_factors+=("System account (UID < $SYSTEM_UID_THRESHOLD)")
    fi
    
    echo "Risk Level: $risk_level"
    echo "Risk Factors:"
    for factor in "${risk_factors[@]}"; do
        echo "  - $factor"
    done
    
    # Privilege Analysis
    echo ""
    echo "== Privilege Analysis =="
    echo "Group Memberships:"
    for group in $groups; do
        local group_info=""
        case "$group" in
            "admin") group_info="Administrative access" ;;
            "wheel") group_info="Sudo privileges" ;;
            "_developer") group_info="Developer tools access" ;;
            "staff") group_info="Standard user group" ;;
            *) group_info="Standard group" ;;
        esac
        echo "  $group - $group_info"
    done
    
    # sudo access check
    echo ""
    echo "== Sudo Access Check =="
    if sudo -l -U "$username" &>/dev/null; then
        echo "Sudo Access: GRANTED"
        echo "Sudo Rules:"
        sudo -l -U "$username" 2>/dev/null | grep -v "may run"
    else
        echo "Sudo Access: DENIED"
    fi
    
    # Recent activity check
    echo ""
    echo "== Recent Activity =="
    echo "Recent Logins:"
    last "$username" | head -5
    
    log_operation "INFO" "Security analysis completed for user: $username (Risk: $risk_level)"
}

# Generate comprehensive user audit report
generate_user_audit_report() {
    local report_type="${1:-summary}"
    local output_format="${2:-text}"
    local requested_by=$(whoami)
    
    local report_file="$REPORT_DIR/user_audit_$(date +%Y%m%d_%H%M%S).$output_format"
    
    log_audit_query "AUDIT_REPORT" "all" "$requested_by" "comprehensive_audit"
    
    {
        echo "MacFleet User Audit Report"
        echo "=========================="
        echo "Report Type: $report_type"
        echo "Generated: $(date)"
        echo "Generated by: $requested_by"
        echo "Hostname: $(hostname)"
        echo ""
        
        case "$report_type" in
            "summary")
                echo "== User Summary =="
                local total_users=$(dscl . list /Users | grep -v '^_' | wc -l)
                local system_users=$(dscl . list /Users UniqueID | awk '$2 < '$SYSTEM_UID_THRESHOLD' {count++} END {print count+0}')
                local regular_users=$((total_users - system_users))
                local admin_users=$(dseditgroup -o checkmember -m admin 2>/dev/null | wc -l)
                
                echo "Total Users: $total_users"
                echo "System Accounts: $system_users"
                echo "Regular Users: $regular_users"
                echo "Administrative Users: $admin_users"
                ;;
            "detailed")
                echo "== Detailed User Analysis =="
                list_users_classified "true" "table"
                ;;
            "security")
                echo "== Security Assessment =="
                echo "High-Privilege Users:"
                for user in $(dscl . list /Users); do
                    if [[ ! "$user" =~ ^_ ]]; then
                        local groups=$(groups "$user" 2>/dev/null | cut -d: -f2)
                        if echo "$groups" | grep -q -E "(admin|wheel|_developer)"; then
                            echo "  $user: $groups"
                        fi
                    fi
                done
                ;;
        esac
        
        echo ""
        echo "== Recent Audit Activity =="
        if [[ -f "$AUDIT_LOG" ]]; then
            echo "Recent queries (last 10):"
            tail -10 "$AUDIT_LOG"
        else
            echo "No audit log available"
        fi
        
        echo ""
        echo "== Compliance Notes =="
        echo "- All user queries are logged for audit purposes"
        echo "- Sensitive attributes are protected by privacy filters"
        echo "- Administrative access is tracked and monitored"
        echo "- Report generated in compliance with enterprise security policies"
        
    } > "$report_file"
    
    echo "User audit report generated: $report_file"
    log_operation "INFO" "User audit report generated by $requested_by: $report_file"
}

# Find users by criteria
find_users_by_criteria() {
    local criteria="$1"
    local value="$2"
    local requested_by=$(whoami)
    
    log_audit_query "SEARCH_USERS" "$criteria:$value" "$requested_by" "criteria_search"
    
    echo "=== User Search Results ==="
    echo "Criteria: $criteria"
    echo "Value: $value"
    echo "Search Time: $(date)"
    echo ""
    
    local found_users=()
    
    case "$criteria" in
        "uid")
            local users=($(dscl . list /Users UniqueID | awk -v val="$value" '$2 == val {print $1}'))
            found_users=("${users[@]}")
            ;;
        "gid")
            local users=($(dscl . list /Users PrimaryGroupID | awk -v val="$value" '$2 == val {print $1}'))
            found_users=("${users[@]}")
            ;;
        "group")
            local group_members=$(dseditgroup -o checkmember -m "$value" 2>/dev/null)
            if [[ $? -eq 0 ]]; then
                found_users=("$value")
            fi
            ;;
        "shell")
            local users=($(dscl . list /Users UserShell | grep "$value" | awk '{print $1}'))
            found_users=("${users[@]}")
            ;;
        "home")
            local users=($(dscl . list /Users NFSHomeDirectory | grep "$value" | awk '{print $1}'))
            found_users=("${users[@]}")
            ;;
        *)
            echo "Error: Unknown search criteria '$criteria'"
            echo "Supported criteria: uid, gid, group, shell, home"
            return 1
            ;;
    esac
    
    if [[ ${#found_users[@]} -eq 0 ]]; then
        echo "No users found matching criteria"
    else
        echo "Found ${#found_users[@]} user(s):"
        for user in "${found_users[@]}"; do
            echo "  $user"
        done
    fi
    
    log_operation "INFO" "User search completed: $criteria=$value, found ${#found_users[@]} users"
}

# Main user details management function
main() {
    local action="${1:-help}"
    
    case "$action" in
        "list")
            local include_system="${2:-false}"
            local format="${3:-table}"
            
            list_users_classified "$include_system" "$format"
            ;;
        "details")
            local username="$2"
            local privacy_filter="${3:-true}"
            
            if [[ -z "$username" ]]; then
                echo "Usage: $0 details <username> [privacy_filter]"
                exit 1
            fi
            
            get_user_details "$username" "$privacy_filter"
            ;;
        "security")
            local username="$2"
            
            if [[ -z "$username" ]]; then
                echo "Usage: $0 security <username>"
                exit 1
            fi
            
            analyze_user_security "$username"
            ;;
        "search")
            local criteria="$2"
            local value="$3"
            
            if [[ -z "$criteria" || -z "$value" ]]; then
                echo "Usage: $0 search <criteria> <value>"
                echo "Criteria: uid, gid, group, shell, home"
                exit 1
            fi
            
            find_users_by_criteria "$criteria" "$value"
            ;;
        "report")
            local report_type="${2:-summary}"
            local output_format="${3:-text}"
            
            generate_user_audit_report "$report_type" "$output_format"
            ;;
        "help"|*)
            echo "$SCRIPT_NAME v$VERSION"
            echo "Enterprise User Details Management"
            echo ""
            echo "Usage: $0 <action> [options]"
            echo ""
            echo "Actions:"
            echo "  list [include_system] [format]           - List all users with classification"
            echo "  details <username> [privacy_filter]     - Get comprehensive user details"
            echo "  security <username>                      - Analyze user security and privileges"
            echo "  search <criteria> <value>                - Find users by specific criteria"
            echo "  report [type] [format]                   - Generate user audit reports"
            echo "  help                                     - Show this help message"
            echo ""
            echo "Options:"
            echo "  include_system: true/false (default: false)"
            echo "  format: table/csv (default: table)"
            echo "  privacy_filter: true/false (default: true)"
            echo "  criteria: uid, gid, group, shell, home"
            echo "  type: summary, detailed, security (default: summary)"
            echo ""
            echo "Features:"
            echo "  • Comprehensive user information retrieval"
            echo "  • Security risk assessment and privilege analysis"
            echo "  • Privacy-protected sensitive attribute handling"
            echo "  • Detailed audit logging for compliance"
            echo "  • Multiple output formats (table, CSV)"
            echo "  • Advanced search and filtering capabilities"
            echo "  • Enterprise-grade reporting and analytics"
            ;;
    esac
}

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

Quick Reference Commands

User Listing Operations

# List all regular users (excluding system accounts)
./user_manager.sh list

# List all users including system accounts
./user_manager.sh list true

# List users in CSV format
./user_manager.sh list false csv

# List all users with system accounts in CSV
./user_manager.sh list true csv

User Details Retrieval

# Get standard user details
./user_manager.sh details john.doe

# Get detailed user information (admin only)
./user_manager.sh details john.doe false

# Get user details with privacy filtering
./user_manager.sh details admin.user true

Security Analysis

# Analyze user security and privileges
./user_manager.sh security john.doe

# Security analysis for admin user
./user_manager.sh security admin.user

# Analyze system account security
./user_manager.sh security root

User Search Operations

# Find users by UID
./user_manager.sh search uid 501

# Find users by group membership
./user_manager.sh search group admin

# Find users by shell
./user_manager.sh search shell "/bin/zsh"

# Find users by home directory pattern
./user_manager.sh search home "/Users"

Reporting Operations

# Generate summary audit report
./user_manager.sh report

# Generate detailed user report
./user_manager.sh report detailed

# Generate security-focused report
./user_manager.sh report security

# Generate CSV report
./user_manager.sh report summary csv

Integration Examples

JAMF Pro Integration

#!/bin/bash

# JAMF Pro script for enterprise user details management
# Parameters: $4 = action, $5 = username, $6 = options

ACTION="$4"
USERNAME="$5"
OPTIONS="$6"

# Download user manager if not present
if [[ ! -f "/usr/local/bin/macfleet_user_manager.sh" ]]; then
    curl -o "/usr/local/bin/macfleet_user_manager.sh" "https://scripts.macfleet.com/user_manager.sh"
    chmod +x "/usr/local/bin/macfleet_user_manager.sh"
fi

# Execute user management operation
case "$ACTION" in
    "audit")
        /usr/local/bin/macfleet_user_manager.sh report detailed text
        ;;
    "security")
        /usr/local/bin/macfleet_user_manager.sh security "$USERNAME"
        ;;
    "list")
        /usr/local/bin/macfleet_user_manager.sh list true csv
        ;;
    *)
        echo "Invalid action: $ACTION"
        exit 1
        ;;
esac

exit $?

Active Directory Integration

#!/bin/bash

# Sync user information with Active Directory
sync_with_active_directory() {
    local ad_domain="company.local"
    local ldap_server="ldap://dc.company.local"
    
    echo "Syncing MacFleet user data with Active Directory..."
    
    # Get local users
    local local_users=($(dscl . list /Users | grep -v '^_'))
    
    for username in "${local_users[@]}"; do
        local uid=$(dscl . -read "/Users/$username" UniqueID 2>/dev/null | awk '{print $2}')
        
        # Skip system accounts
        if [[ $uid -lt 500 ]]; then
            continue
        fi
        
        # Query AD for user information
        local ad_info=$(ldapsearch -H "$ldap_server" -b "DC=company,DC=local" "(sAMAccountName=$username)" 2>/dev/null)
        
        if [[ -n "$ad_info" ]]; then
            echo "User $username found in AD: Syncing attributes..."
            # Sync logic would go here
        else
            echo "User $username not found in AD: Local account only"
        fi
    done
}

Compliance and Privacy Features

Privacy Protection

# Privacy-compliant user information handling
get_privacy_compliant_details() {
    local username="$1"
    local requester="$2"
    local purpose="$3"
    
    # Log privacy-sensitive access
    echo "PRIVACY_ACCESS|$(date)|$username|$requester|$purpose" >> "/var/log/privacy_access.log"
    
    # Filter sensitive attributes based on requester permissions
    if [[ "$requester" != "root" ]]; then
        # Remove sensitive fields for non-root users
        dscl . -read "/Users/$username" | grep -v -E "(Password|ShadowHashData|JPEGPhoto)"
    else
        # Full access for root with audit logging
        dscl . -read "/Users/$username"
    fi
}

GDPR Compliance

# GDPR-compliant user data export
export_user_data_gdpr() {
    local username="$1"
    local export_file="/tmp/user_export_${username}_$(date +%s).json"
    
    # Log data export request
    log_operation "GDPR_EXPORT" "Data export requested for user: $username"
    
    # Create structured JSON export
    {
        echo "{"
        echo "  \"export_timestamp\": \"$(date -u +%Y-%m-%dT%H:%M:%SZ)\","
        echo "  \"username\": \"$username\","
        echo "  \"personal_data\": {"
        
        # Include only GDPR-relevant personal data
        local real_name=$(dscl . -read "/Users/$username" RealName 2>/dev/null | sed 's/RealName: //')
        echo "    \"real_name\": \"$real_name\","
        echo "    \"home_directory\": \"$(dscl . -read "/Users/$username" NFSHomeDirectory | awk '{print $2}')\","
        echo "    \"creation_date\": \"$(stat -f %SB /Users/$username 2>/dev/null)\""
        
        echo "  },"
        echo "  \"compliance_note\": \"This export contains personal data as defined by GDPR Article 4(1)\""
        echo "}"
    } > "$export_file"
    
    echo "GDPR data export created: $export_file"
}

Best Practices

  1. Implement role-based access for user information retrieval
  2. Enable comprehensive audit logging for all user queries
  3. Use privacy filters to protect sensitive user attributes
  4. Regular security assessments of high-privilege accounts
  5. Integrate with enterprise directory services for centralized management
  6. Monitor for unusual user activity patterns
  7. Generate regular compliance reports for auditing purposes
  8. Protect sensitive user data according to privacy regulations

This enterprise user details management system provides comprehensive user information retrieval, security analysis, and audit capabilities while maintaining privacy protection and compliance standards for effective MacFleet user management.

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.