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.

User Creation Management on macOS

Efficiently create and provision user accounts across your MacFleet deployment with enterprise-grade user lifecycle management, automated workflows, and comprehensive security controls. This tutorial transforms basic dscl and sysadminctl commands into robust user provisioning solutions.

Understanding Enterprise User Creation Management

Enterprise user creation requires more than basic account provisioning, demanding:

  • Automated user provisioning workflows with template-based configuration
  • Security-first account creation with proper privilege assignment
  • Standardized user onboarding with consistent directory structures
  • Integration capabilities with enterprise identity systems
  • Audit logging for compliance and security monitoring
  • Bulk user operations for efficient fleet management

Core User Creation Operations

Basic User Creation Commands

# dscl-based user creation
sudo dscl . -create /Users/Username
sudo dscl . -create /Users/Username RealName "John Doe"
sudo dscl . -passwd /Users/Username password_here
sudo dscl . -create /Users/Username UniqueID 1088
sudo dscl . -create /Users/Username PrimaryGroupID 20
sudo dscl . -create /Users/Username UserShell /bin/bash
sudo dscl . -create /Users/Username NFSHomeDirectory /Users/Username

# sysadminctl-based user creation
sysadminctl -addUser <username> -password <password>

These utilize the directory service command-line utility (dscl) and system administrator control (sysadminctl) for user account management.

Enterprise User Creation Management System

#!/bin/bash

# MacFleet Enterprise User Creation Management System
# Comprehensive user provisioning with enterprise controls and automation

# Configuration
SCRIPT_NAME="MacFleet User Creation Manager"
VERSION="1.0.0"
LOG_FILE="/var/log/macfleet_user_creation.log"
AUDIT_LOG="/var/log/macfleet_user_audit.log"
TEMPLATES_DIR="/etc/macfleet/user_templates"
PROVISIONING_DIR="/var/lib/macfleet/provisioning"
TEMP_DIR="/tmp/macfleet_users"
MIN_UID=1000
MAX_UID=65000
DEFAULT_SHELL="/bin/zsh"
HOME_BASE_DIR="/Users"
COMPANY_DOMAIN="company.local"
REQUIRE_SECURE_PASSWORDS=true
ENFORCE_NAMING_CONVENTION=true
AUTO_FILEVAULT_ENABLE=true
STANDARD_GROUPS=("staff" "_appserverusr" "_appserveradm")
ADMIN_GROUPS=("admin" "staff" "_developer")
DEVELOPER_GROUPS=("staff" "_developer" "_appserverusr")

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

# Set secure permissions
chmod 700 "$TEMP_DIR"
chmod 750 "$PROVISIONING_DIR"
chmod 755 "$TEMPLATES_DIR"

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

log_audit_action() {
    local action_type="$1"
    local target_user="$2"
    local performed_by="$3"
    local details="$4"
    
    local timestamp=$(date '+%Y-%m-%d %H:%M:%S')
    local source_ip=$(who am i | awk '{print $5}' | tr -d '()')
    echo "ACTION|$timestamp|$action_type|$target_user|$performed_by|$source_ip|$details" >> "$AUDIT_LOG"
}

# Generate secure random password
generate_secure_password() {
    local length="${1:-12}"
    local complexity="${2:-high}"
    
    case "$complexity" in
        "high")
            # High complexity: uppercase, lowercase, numbers, symbols
            openssl rand -base64 32 | tr -d "=+/" | cut -c1-${length}
            ;;
        "medium")
            # Medium complexity: uppercase, lowercase, numbers
            LC_ALL=C tr -dc 'A-Za-z0-9' </dev/urandom | head -c ${length}
            ;;
        "basic")
            # Basic complexity: lowercase and numbers
            LC_ALL=C tr -dc 'a-z0-9' </dev/urandom | head -c ${length}
            ;;
        *)
            echo "Error: Unknown complexity level"
            return 1
            ;;
    esac
}

# Validate password policy
validate_password() {
    local password="$1"
    local min_length=8
    local errors=()
    
    # Check minimum length
    if [[ ${#password} -lt $min_length ]]; then
        errors+=("Password must be at least $min_length characters")
    fi
    
    # Check for uppercase letter
    if [[ ! "$password" =~ [A-Z] ]]; then
        errors+=("Password must contain at least one uppercase letter")
    fi
    
    # Check for lowercase letter
    if [[ ! "$password" =~ [a-z] ]]; then
        errors+=("Password must contain at least one lowercase letter")
    fi
    
    # Check for number
    if [[ ! "$password" =~ [0-9] ]]; then
        errors+=("Password must contain at least one number")
    fi
    
    # Check for special character
    if [[ ! "$password" =~ [^A-Za-z0-9] ]]; then
        errors+=("Password must contain at least one special character")
    fi
    
    if [[ ${#errors[@]} -gt 0 ]]; then
        echo "Password validation failed:"
        printf '  - %s\n' "${errors[@]}"
        return 1
    fi
    
    return 0
}

# Validate username according to enterprise naming convention
validate_username() {
    local username="$1"
    local errors=()
    
    # Check length (3-20 characters)
    if [[ ${#username} -lt 3 || ${#username} -gt 20 ]]; then
        errors+=("Username must be 3-20 characters long")
    fi
    
    # Check for valid characters (alphanumeric, dots, hyphens, underscores)
    if [[ ! "$username" =~ ^[a-zA-Z0-9._-]+$ ]]; then
        errors+=("Username can only contain letters, numbers, dots, hyphens, and underscores")
    fi
    
    # Check that it starts with a letter
    if [[ ! "$username" =~ ^[a-zA-Z] ]]; then
        errors+=("Username must start with a letter")
    fi
    
    # Check for reserved usernames
    local reserved_names=("admin" "root" "daemon" "nobody" "wheel" "operator" "system")
    for reserved in "${reserved_names[@]}"; do
        if [[ "$username" == "$reserved" ]]; then
            errors+=("Username '$username' is reserved")
        fi
    done
    
    # Check if username already exists
    if dscl . -read "/Users/$username" &>/dev/null; then
        errors+=("Username '$username' already exists")
    fi
    
    if [[ ${#errors[@]} -gt 0 ]]; then
        echo "Username validation failed:"
        printf '  - %s\n' "${errors[@]}"
        return 1
    fi
    
    return 0
}

# Find next available UID
find_next_uid() {
    local start_uid="${1:-$MIN_UID}"
    local max_uid="${2:-$MAX_UID}"
    
    # Get all existing UIDs
    local existing_uids=($(dscl . list /Users UniqueID | awk '{print $2}' | sort -n))
    
    # Find first available UID
    for ((uid=start_uid; uid<=max_uid; uid++)); do
        local uid_exists=false
        for existing_uid in "${existing_uids[@]}"; do
            if [[ $uid -eq $existing_uid ]]; then
                uid_exists=true
                break
            fi
        done
        
        if [[ "$uid_exists" == "false" ]]; then
            echo "$uid"
            return 0
        fi
    done
    
    echo "Error: No available UID found in range $start_uid-$max_uid"
    return 1
}

# Create user account with enterprise settings
create_enterprise_user() {
    local username="$1"
    local real_name="$2"
    local password="$3"
    local user_type="${4:-standard}"
    local department="${5:-General}"
    local admin_user=$(whoami)
    
    log_audit_action "USER_CREATION_START" "$username" "$admin_user" "type=$user_type,department=$department"
    
    # Validate inputs
    if ! validate_username "$username"; then
        log_operation "ERROR" "Username validation failed for: $username"
        return 1
    fi
    
    if [[ "$REQUIRE_SECURE_PASSWORDS" == "true" ]] && ! validate_password "$password"; then
        log_operation "ERROR" "Password validation failed for user: $username"
        return 1
    fi
    
    # Find available UID
    local uid
    uid=$(find_next_uid)
    if [[ $? -ne 0 ]]; then
        log_operation "ERROR" "Failed to find available UID for: $username"
        return 1
    fi
    
    echo "=== Creating Enterprise User: $username ==="
    echo "Real Name: $real_name"
    echo "User Type: $user_type"
    echo "Department: $department"
    echo "Assigned UID: $uid"
    echo "Administrator: $admin_user"
    echo ""
    
    # Create user account using dscl
    echo "Creating user account..."
    
    # Basic user creation
    if ! sudo dscl . -create "/Users/$username"; then
        log_operation "ERROR" "Failed to create user: $username"
        return 1
    fi
    
    # Set real name
    sudo dscl . -create "/Users/$username" RealName "$real_name"
    
    # Set password
    sudo dscl . -passwd "/Users/$username" "$password"
    
    # Set UID
    sudo dscl . -create "/Users/$username" UniqueID "$uid"
    
    # Determine primary group ID based on user type
    local primary_gid
    case "$user_type" in
        "admin")
            primary_gid=80  # admin group
            ;;
        "developer")
            primary_gid=20  # staff group
            ;;
        "standard"|*)
            primary_gid=20  # staff group
            ;;
    esac
    
    sudo dscl . -create "/Users/$username" PrimaryGroupID "$primary_gid"
    
    # Set shell
    sudo dscl . -create "/Users/$username" UserShell "$DEFAULT_SHELL"
    
    # Create home directory
    local home_dir="$HOME_BASE_DIR/$username"
    sudo dscl . -create "/Users/$username" NFSHomeDirectory "$home_dir"
    
    # Add enterprise attributes
    sudo dscl . -create "/Users/$username" Department "$department"
    sudo dscl . -create "/Users/$username" Company "$(hostname -s | cut -d. -f1)"
    sudo dscl . -create "/Users/$username" CreationDate "$(date)"
    sudo dscl . -create "/Users/$username" CreatedBy "$admin_user"
    
    # Add password hint
    sudo dscl . -create "/Users/$username" hint "Contact IT support for password assistance"
    
    # Set up group memberships based on user type
    echo "Configuring group memberships..."
    case "$user_type" in
        "admin")
            for group in "${ADMIN_GROUPS[@]}"; do
                sudo dseditgroup -o edit -a "$username" -t user "$group" 2>/dev/null
            done
            ;;
        "developer")
            for group in "${DEVELOPER_GROUPS[@]}"; do
                sudo dseditgroup -o edit -a "$username" -t user "$group" 2>/dev/null
            done
            ;;
        "standard"|*)
            for group in "${STANDARD_GROUPS[@]}"; do
                sudo dseditgroup -o edit -a "$username" -t user "$group" 2>/dev/null
            done
            ;;
    esac
    
    # Create and configure home directory
    echo "Setting up home directory..."
    if [[ ! -d "$home_dir" ]]; then
        sudo mkdir -p "$home_dir"
        sudo chown "$username:staff" "$home_dir"
        sudo chmod 755 "$home_dir"
    fi
    
    # Copy user template if available
    local template_dir="$TEMPLATES_DIR/$user_type"
    if [[ -d "$template_dir" ]]; then
        echo "Applying user template: $user_type"
        sudo cp -R "$template_dir/"* "$home_dir/" 2>/dev/null
        sudo chown -R "$username:staff" "$home_dir"
    fi
    
    # Enable FileVault for new user if required
    if [[ "$AUTO_FILEVAULT_ENABLE" == "true" ]]; then
        echo "Enabling FileVault access for user..."
        sudo fdesetup add -usertoadd "$username" 2>/dev/null || true
    fi
    
    # Generate user profile report
    local profile_file="$PROVISIONING_DIR/${username}_profile.txt"
    {
        echo "MacFleet User Profile"
        echo "===================="
        echo "Username: $username"
        echo "Real Name: $real_name"
        echo "UID: $uid"
        echo "GID: $primary_gid"
        echo "User Type: $user_type"
        echo "Department: $department"
        echo "Home Directory: $home_dir"
        echo "Shell: $DEFAULT_SHELL"
        echo "Created: $(date)"
        echo "Created By: $admin_user"
        echo "Groups: $(groups "$username" 2>/dev/null | cut -d: -f2)"
        echo ""
        echo "Security Settings:"
        echo "- FileVault Enabled: $AUTO_FILEVAULT_ENABLE"
        echo "- Secure Password: $REQUIRE_SECURE_PASSWORDS"
        echo "- Naming Convention: $ENFORCE_NAMING_CONVENTION"
    } > "$profile_file"
    
    echo "✅ User creation completed successfully"
    echo "Profile saved: $profile_file"
    
    log_operation "INFO" "User created successfully: $username (UID: $uid, Type: $user_type)"
    log_audit_action "USER_CREATION_SUCCESS" "$username" "$admin_user" "uid=$uid,type=$user_type,groups=$(groups "$username" 2>/dev/null | cut -d: -f2)"
    
    return 0
}

# Bulk user creation from CSV file
bulk_create_users() {
    local csv_file="$1"
    local admin_user=$(whoami)
    
    if [[ ! -f "$csv_file" ]]; then
        echo "Error: CSV file not found: $csv_file"
        return 1
    fi
    
    log_audit_action "BULK_CREATION_START" "multiple" "$admin_user" "source=$csv_file"
    
    echo "=== Bulk User Creation ==="
    echo "CSV File: $csv_file"
    echo "Administrator: $admin_user"
    echo ""
    
    local line_count=0
    local success_count=0
    local error_count=0
    local results_file="$PROVISIONING_DIR/bulk_creation_$(date +%Y%m%d_%H%M%S).log"
    
    # Read CSV file (format: username,real_name,user_type,department)
    while IFS=',' read -r username real_name user_type department; do
        line_count=$((line_count + 1))
        
        # Skip header line
        if [[ $line_count -eq 1 && "$username" == "username" ]]; then
            continue
        fi
        
        # Skip empty lines
        if [[ -z "$username" ]]; then
            continue
        fi
        
        # Generate secure password
        local password
        password=$(generate_secure_password 12 "high")
        
        echo "Processing user $line_count: $username"
        
        # Create user
        if create_enterprise_user "$username" "$real_name" "$password" "$user_type" "$department"; then
            success_count=$((success_count + 1))
            echo "SUCCESS: $username,$real_name,$password,$user_type,$department" >> "$results_file"
        else
            error_count=$((error_count + 1))
            echo "ERROR: $username,$real_name,FAILED,$user_type,$department" >> "$results_file"
        fi
        
        echo ""
    done < "$csv_file"
    
    echo "=== Bulk Creation Summary ==="
    echo "Total Processed: $line_count"
    echo "Successful: $success_count"
    echo "Errors: $error_count"
    echo "Results File: $results_file"
    
    log_operation "INFO" "Bulk user creation completed: $success_count successful, $error_count errors"
    log_audit_action "BULK_CREATION_COMPLETE" "multiple" "$admin_user" "total=$line_count,success=$success_count,errors=$error_count"
}

# Create user templates
create_user_template() {
    local template_type="$1"
    local template_dir="$TEMPLATES_DIR/$template_type"
    
    echo "Creating user template: $template_type"
    
    mkdir -p "$template_dir"
    
    case "$template_type" in
        "standard")
            # Standard user template
            mkdir -p "$template_dir/Desktop"
            mkdir -p "$template_dir/Documents"
            mkdir -p "$template_dir/Downloads"
            
            # Create welcome document
            cat > "$template_dir/Desktop/Welcome.txt" << EOF
Welcome to MacFleet!

Your account has been set up with standard user privileges.
For support, please contact IT at support@company.com

Account Type: Standard User
Creation Date: $(date)
EOF
            ;;
        "admin")
            # Admin user template
            mkdir -p "$template_dir/Desktop"
            mkdir -p "$template_dir/Documents/AdminTools"
            mkdir -p "$template_dir/Downloads"
            
            cat > "$template_dir/Desktop/Admin_Welcome.txt" << EOF
Welcome to MacFleet - Administrator Account

Your account has been configured with administrative privileges.
Please use these privileges responsibly.

Account Type: Administrator
Creation Date: $(date)

Important:
- Follow company security policies
- Regular password changes required
- All administrative actions are logged
EOF
            ;;
        "developer")
            # Developer user template
            mkdir -p "$template_dir/Desktop"
            mkdir -p "$template_dir/Documents/Projects"
            mkdir -p "$template_dir/Downloads"
            mkdir -p "$template_dir/Development"
            
            cat > "$template_dir/Desktop/Developer_Setup.txt" << EOF
Developer Account Setup

Your account includes development tools access.

Account Type: Developer
Creation Date: $(date)

Next Steps:
1. Install Xcode from App Store
2. Configure Git credentials
3. Set up development environment
4. Review coding standards documentation
EOF
            ;;
    esac
    
    # Set template permissions
    chmod -R 755 "$template_dir"
    
    echo "Template created: $template_dir"
    log_operation "INFO" "User template created: $template_type"
}

# Generate provisioning report
generate_provisioning_report() {
    local report_type="${1:-summary}"
    local admin_user=$(whoami)
    local report_file="$PROVISIONING_DIR/provisioning_report_$(date +%Y%m%d_%H%M%S).txt"
    
    log_audit_action "PROVISIONING_REPORT" "system" "$admin_user" "type=$report_type"
    
    {
        echo "MacFleet User Provisioning Report"
        echo "================================="
        echo "Report Type: $report_type"
        echo "Generated: $(date)"
        echo "Generated By: $admin_user"
        echo "Hostname: $(hostname)"
        echo ""
        
        case "$report_type" in
            "summary")
                echo "== Provisioning Summary =="
                local total_users=$(dscl . list /Users | grep -v '^_' | wc -l)
                local recent_users=$(find "$PROVISIONING_DIR" -name "*_profile.txt" -mtime -7 | wc -l)
                
                echo "Total Users: $total_users"
                echo "Users Created (Last 7 days): $recent_users"
                echo ""
                
                echo "User Type Distribution:"
                echo "Standard Users: $(dscl . list /Users | xargs -I {} dscl . read /Users/{} PrimaryGroupID 2>/dev/null | grep -c '20')"
                echo "Admin Users: $(dscl . list /Users | xargs -I {} dscl . read /Users/{} PrimaryGroupID 2>/dev/null | grep -c '80')"
                ;;
            "recent")
                echo "== Recent User Creations =="
                echo "Users created in last 30 days:"
                find "$PROVISIONING_DIR" -name "*_profile.txt" -mtime -30 -exec basename {} \; | sed 's/_profile.txt//'
                ;;
            "audit")
                echo "== Audit Information =="
                if [[ -f "$AUDIT_LOG" ]]; then
                    echo "Recent provisioning activities:"
                    grep "USER_CREATION" "$AUDIT_LOG" | tail -10
                else
                    echo "No audit log available"
                fi
                ;;
        esac
        
        echo ""
        echo "== Configuration =="
        echo "Min UID: $MIN_UID"
        echo "Max UID: $MAX_UID"
        echo "Default Shell: $DEFAULT_SHELL"
        echo "Auto FileVault: $AUTO_FILEVAULT_ENABLE"
        echo "Secure Passwords: $REQUIRE_SECURE_PASSWORDS"
        echo "Naming Convention: $ENFORCE_NAMING_CONVENTION"
        
    } > "$report_file"
    
    echo "Provisioning report generated: $report_file"
    log_operation "INFO" "Provisioning report generated: $report_file"
}

# Main user creation management function
main() {
    local action="${1:-help}"
    
    case "$action" in
        "create")
            local username="$2"
            local real_name="$3"
            local password="$4"
            local user_type="${5:-standard}"
            local department="${6:-General}"
            
            if [[ -z "$username" || -z "$real_name" ]]; then
                echo "Usage: $0 create <username> <real_name> [password] [user_type] [department]"
                echo "User types: standard, admin, developer"
                exit 1
            fi
            
            # Generate password if not provided
            if [[ -z "$password" ]]; then
                password=$(generate_secure_password 12 "high")
                echo "Generated secure password: $password"
            fi
            
            create_enterprise_user "$username" "$real_name" "$password" "$user_type" "$department"
            ;;
        "bulk")
            local csv_file="$2"
            
            if [[ -z "$csv_file" ]]; then
                echo "Usage: $0 bulk <csv_file>"
                echo "CSV format: username,real_name,user_type,department"
                exit 1
            fi
            
            bulk_create_users "$csv_file"
            ;;
        "template")
            local template_type="$2"
            
            if [[ -z "$template_type" ]]; then
                echo "Usage: $0 template <template_type>"
                echo "Template types: standard, admin, developer"
                exit 1
            fi
            
            create_user_template "$template_type"
            ;;
        "report")
            local report_type="${2:-summary}"
            
            generate_provisioning_report "$report_type"
            ;;
        "password")
            local length="${2:-12}"
            local complexity="${3:-high}"
            
            echo "Generated password: $(generate_secure_password "$length" "$complexity")"
            ;;
        "help"|*)
            echo "$SCRIPT_NAME v$VERSION"
            echo "Enterprise User Creation Management"
            echo ""
            echo "Usage: $0 <action> [options]"
            echo ""
            echo "Actions:"
            echo "  create <username> <real_name> [password] [type] [dept]  - Create single user"
            echo "  bulk <csv_file>                                         - Create users from CSV"
            echo "  template <type>                                         - Create user template"
            echo "  report [type]                                           - Generate provisioning reports"
            echo "  password [length] [complexity]                         - Generate secure password"
            echo "  help                                                    - Show this help message"
            echo ""
            echo "User Types:"
            echo "  standard    - Standard user with basic privileges"
            echo "  admin       - Administrative user with elevated privileges"
            echo "  developer   - Developer user with development tools access"
            echo ""
            echo "Report Types:"
            echo "  summary     - Overview of user provisioning (default)"
            echo "  recent      - Recently created users"
            echo "  audit       - Audit trail information"
            echo ""
            echo "Password Complexity:"
            echo "  basic       - Lowercase and numbers only"
            echo "  medium      - Letters and numbers"
            echo "  high        - Letters, numbers, and symbols (default)"
            echo ""
            echo "Features:"
            echo "  • Automated user provisioning with enterprise templates"
            echo "  • Security-first account creation with validation"
            echo "  • Bulk user creation from CSV files"
            echo "  • Comprehensive audit logging and compliance"
            echo "  • Integration with FileVault and enterprise security"
            echo "  • Template-based user onboarding"
            echo "  • Automated password generation and validation"
            ;;
    esac
}

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

Quick Reference Commands

Single User Creation

# Create standard user
./user_creator.sh create john.doe "John Doe"

# Create admin user with custom password
./user_creator.sh create admin.user "Admin User" "SecurePass123!" admin IT

# Create developer user
./user_creator.sh create dev.user "Developer User" "" developer Engineering

# Create user with all parameters
./user_creator.sh create jane.smith "Jane Smith" "CustomPass456!" standard Marketing

Bulk User Operations

# Create users from CSV file
./user_creator.sh bulk users.csv

# CSV format example:
# username,real_name,user_type,department
# john.doe,John Doe,standard,Sales
# jane.admin,Jane Admin,admin,IT
# dev.user,Dev User,developer,Engineering

Template Management

# Create standard user template
./user_creator.sh template standard

# Create admin user template
./user_creator.sh template admin

# Create developer user template
./user_creator.sh template developer

Password Generation

# Generate high-complexity password (default)
./user_creator.sh password

# Generate 16-character password
./user_creator.sh password 16

# Generate medium-complexity password
./user_creator.sh password 12 medium

# Generate basic password
./user_creator.sh password 10 basic

Reporting Operations

# Generate summary report
./user_creator.sh report

# Generate recent users report
./user_creator.sh report recent

# Generate audit report
./user_creator.sh report audit

Advanced User Creation Scenarios

Automated Onboarding Workflow

#!/bin/bash

# Automated new employee onboarding
onboard_employee() {
    local employee_data="$1"  # JSON file with employee details
    
    # Parse employee data
    local username=$(jq -r '.username' "$employee_data")
    local real_name=$(jq -r '.real_name' "$employee_data")
    local department=$(jq -r '.department' "$employee_data")
    local role=$(jq -r '.role' "$employee_data")
    local manager=$(jq -r '.manager' "$employee_data")
    
    # Determine user type based on role
    local user_type="standard"
    case "$role" in
        "Admin"|"IT Manager"|"System Administrator")
            user_type="admin"
            ;;
        "Developer"|"Software Engineer"|"DevOps")
            user_type="developer"
            ;;
    esac
    
    # Create user account
    ./user_creator.sh create "$username" "$real_name" "" "$user_type" "$department"
    
    # Send welcome email with credentials
    send_welcome_email "$username" "$real_name" "$manager"
    
    # Schedule follow-up tasks
    schedule_onboarding_tasks "$username" "$department"
}

Integration with Enterprise Systems

# JAMF Pro integration for user creation
#!/bin/bash

# JAMF Pro script parameters
USERNAME="$4"
REAL_NAME="$5"
USER_TYPE="$6"
DEPARTMENT="$7"

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

# Create user with enterprise settings
/usr/local/bin/macfleet_user_creator.sh create \
    "$USERNAME" "$REAL_NAME" "" "$USER_TYPE" "$DEPARTMENT"

# Report status back to JAMF
if [[ $? -eq 0 ]]; then
    echo "User $USERNAME created successfully"
    exit 0
else
    echo "Failed to create user $USERNAME"
    exit 1
fi

Active Directory Synchronization

#!/bin/bash

# Sync new users with Active Directory
sync_with_active_directory() {
    local username="$1"
    local ad_domain="company.local"
    
    # Wait for user account to be fully created
    sleep 5
    
    # Create AD bind if not exists
    if ! dsconfigad -show | grep -q "Active Directory Domain"; then
        echo "Binding to Active Directory domain: $ad_domain"
        dsconfigad -add "$ad_domain" -username "ad_admin" -password "ad_password"
    fi
    
    # Create mobile account for AD integration
    dscl /Active\ Directory/COMPANY/All\ Domains -create /Users/"$username"
    
    echo "User $username synchronized with Active Directory"
}

Security and Compliance Features

Password Policy Enforcement

# Advanced password policy validation
enforce_enterprise_password_policy() {
    local password="$1"
    local username="$2"
    
    # Check against common passwords
    local common_passwords=("password" "123456" "admin" "welcome")
    for common in "${common_passwords[@]}"; do
        if [[ "${password,,}" == "${common,,}" ]]; then
            echo "Error: Password is too common"
            return 1
        fi
    done
    
    # Check for username in password
    if [[ "${password,,}" =~ ${username,,} ]]; then
        echo "Error: Password cannot contain username"
        return 1
    fi
    
    # Check password history (if implemented)
    check_password_history "$username" "$password"
}

Audit and Compliance Reporting

# Generate compliance report for user creation
generate_compliance_report() {
    local start_date="$1"
    local end_date="$2"
    local report_file="/var/reports/user_creation_compliance_$(date +%Y%m%d).json"
    
    {
        echo "{"
        echo "  \"report_type\": \"user_creation_compliance\","
        echo "  \"period\": \"$start_date to $end_date\","
        echo "  \"generated\": \"$(date -u +%Y-%m-%dT%H:%M:%SZ)\","
        echo "  \"total_users_created\": $(grep "USER_CREATION_SUCCESS" "$AUDIT_LOG" | wc -l),"
        echo "  \"policy_violations\": $(grep "POLICY_VIOLATION" "$AUDIT_LOG" | wc -l),"
        echo "  \"security_reviews\": $(grep "SECURITY_REVIEW" "$AUDIT_LOG" | wc -l)"
        echo "}"
    } > "$report_file"
    
    echo "Compliance report generated: $report_file"
}

Best Practices

  1. Use strong password policies with complexity requirements
  2. Implement role-based user types for appropriate privilege assignment
  3. Enable comprehensive audit logging for all user creation activities
  4. Use templates for consistent user onboarding experiences
  5. Integrate with enterprise directory services for centralized management
  6. Automate FileVault enrollment for security compliance
  7. Generate regular compliance reports for audit purposes
  8. Validate usernames against enterprise naming conventions

This enterprise user creation management system provides comprehensive user provisioning capabilities with security controls, audit compliance, and automated workflows for effective MacFleet user lifecycle management.

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.