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 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

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.