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.

Checking if a User Exists on macOS Devices

Effective user account management is essential for maintaining access control and security in any organization. When managing multiple macOS devices, administrators need reliable methods to verify user account existence across their fleet. This guide provides shell scripts and techniques to efficiently check for user presence on macOS devices.

User verification is particularly important for:

  • Security audits and compliance
  • Access control management
  • Account provisioning and deprovisioning
  • Troubleshooting login issues
  • Fleet management and inventory

Understanding User Accounts on macOS

macOS manages user accounts through various mechanisms:

  • Local user accounts: Created directly on the Mac
  • Network accounts: Managed through directory services (Active Directory, LDAP)
  • Apple ID accounts: Connected to iCloud services
  • Service accounts: System-level accounts for specific services

Each user account has unique identifiers including username, User ID (UID), and group memberships that can be verified programmatically.

Prerequisites

Before implementing these scripts, ensure you have:

  • Administrative access to the Mac devices
  • Terminal or SSH access
  • Basic understanding of bash scripting
  • macOS 10.14 or later (script compatibility)

Basic User Existence Check

The fundamental script to check if a user exists on macOS:

#!/bin/bash

# Basic user existence check
if id -u "User" >/dev/null 2>&1; then
    echo "Yes, the user exists."
else
    echo "No, the user does not exist."
fi

How this script works:

  1. id -u "User": The id command with the -u option returns the User ID (UID) of the specified username
  2. >/dev/null 2>&1: Redirects both standard output and error messages to /dev/null to suppress them
  3. Exit status check: If the user exists, id returns exit status 0 (success), otherwise it returns non-zero (failure)
  4. Conditional execution: The if statement executes different blocks based on the exit status

Enhanced User Verification Script

Here's a more comprehensive script that provides detailed user information:

#!/bin/bash

# Enhanced user verification with detailed information
USERNAME="$1"

if [ -z "$USERNAME" ]; then
    echo "Usage: $0 <username>"
    echo "Example: $0 john.doe"
    exit 1
fi

echo "Checking user: $USERNAME"
echo "================================"

if id -u "$USERNAME" >/dev/null 2>&1; then
    echo "✓ User exists"
    
    # Get user details
    USER_ID=$(id -u "$USERNAME")
    GROUP_ID=$(id -g "$USERNAME")
    USER_GROUPS=$(id -Gn "$USERNAME")
    HOME_DIR=$(eval echo ~$USERNAME)
    
    echo "User ID (UID): $USER_ID"
    echo "Primary Group ID (GID): $GROUP_ID"
    echo "Group memberships: $USER_GROUPS"
    echo "Home directory: $HOME_DIR"
    
    # Check if home directory exists
    if [ -d "$HOME_DIR" ]; then
        echo "✓ Home directory exists"
        echo "Home directory size: $(du -sh "$HOME_DIR" 2>/dev/null | cut -f1)"
    else
        echo "✗ Home directory does not exist"
    fi
    
    # Check if user is currently logged in
    if who | grep -q "^$USERNAME "; then
        echo "✓ User is currently logged in"
    else
        echo "- User is not currently logged in"
    fi
    
else
    echo "✗ User does not exist"
    echo "Available users:"
    dscl . -list /Users | grep -v "^_" | head -10
fi

Batch User Verification

For checking multiple users at once:

#!/bin/bash

# Batch user verification script
USERS=("john.doe" "jane.smith" "admin" "test.user")

echo "Batch User Verification Report"
echo "=============================="
echo "Date: $(date)"
echo ""

for username in "${USERS[@]}"; do
    if id -u "$username" >/dev/null 2>&1; then
        user_id=$(id -u "$username")
        echo "✓ $username (UID: $user_id) - EXISTS"
    else
        echo "✗ $username - DOES NOT EXIST"
    fi
done

echo ""
echo "Verification complete."

Advanced User Management Scripts

Script to List All Users

#!/bin/bash

# List all users on the system
echo "System Users Report"
echo "==================="
echo ""

echo "Regular Users (UID >= 500):"
echo "----------------------------"
dscl . -list /Users UniqueID | awk '$2 >= 500 {print $1 " (UID: " $2 ")"}' | sort -n -k3

echo ""
echo "System Users (UID < 500):"
echo "-------------------------"
dscl . -list /Users UniqueID | awk '$2 < 500 {print $1 " (UID: " $2 ")"}' | sort -n -k3

echo ""
echo "Currently Logged In Users:"
echo "-------------------------"
who | awk '{print $1}' | sort | uniq

Script to Check User Account Status

#!/bin/bash

# Check comprehensive user account status
USERNAME="$1"

if [ -z "$USERNAME" ]; then
    echo "Usage: $0 <username>"
    exit 1
fi

echo "Comprehensive User Status: $USERNAME"
echo "===================================="

if id -u "$USERNAME" >/dev/null 2>&1; then
    echo "✓ User account exists"
    
    # Check if account is enabled
    if dscl . -read /Users/$USERNAME AuthenticationAuthority 2>/dev/null | grep -q "DisabledUser"; then
        echo "✗ Account is DISABLED"
    else
        echo "✓ Account is ENABLED"
    fi
    
    # Check password policy
    pwpolicy -u "$USERNAME" -getaccountpolicies 2>/dev/null | grep -q "policyCategories" && echo "✓ Password policy applied" || echo "- No specific password policy"
    
    # Check admin privileges
    if groups "$USERNAME" | grep -q "admin"; then
        echo "⚠ User has ADMIN privileges"
    else
        echo "✓ User has standard privileges"
    fi
    
    # Check last login
    last -1 "$USERNAME" | head -1 | grep -q "wtmp begins" && echo "- No login history found" || echo "Last login: $(last -1 "$USERNAME" | head -1 | awk '{print $4, $5, $6, $7}')"
    
else
    echo "✗ User account does not exist"
fi

Remote User Verification

For managing multiple Mac devices remotely:

#!/bin/bash

# Remote user verification across multiple Macs
HOSTS=(
    "mac1.local"
    "mac2.local"
    "mac3.local"
)

USERNAME="$1"

if [ -z "$USERNAME" ]; then
    echo "Usage: $0 <username>"
    echo "Example: $0 john.doe"
    exit 1
fi

echo "Remote User Verification: $USERNAME"
echo "=================================="
echo ""

for host in "${HOSTS[@]}"; do
    echo "Checking $host..."
    
    if ping -c 1 -W 1000 "$host" >/dev/null 2>&1; then
        # Create a simple check script
        check_script="if id -u '$USERNAME' >/dev/null 2>&1; then echo 'EXISTS'; else echo 'NOT_FOUND'; fi"
        
        result=$(ssh -o ConnectTimeout=5 -o BatchMode=yes "$host" "$check_script" 2>/dev/null)
        
        if [ "$result" = "EXISTS" ]; then
            echo "  ✓ $host - User exists"
        elif [ "$result" = "NOT_FOUND" ]; then
            echo "  ✗ $host - User not found"
        else
            echo "  ⚠ $host - Unable to verify (SSH error)"
        fi
    else
        echo "  ✗ $host - Host unreachable"
    fi
done

Automated Reporting

Create automated reports for user account management:

#!/bin/bash

# Automated user existence report
REPORT_FILE="user_report_$(date +%Y%m%d_%H%M%S).txt"
USERS_TO_CHECK=("admin" "guest" "support" "developer")

{
    echo "User Existence Report"
    echo "===================="
    echo "Generated: $(date)"
    echo "Hostname: $(hostname)"
    echo "macOS Version: $(sw_vers -productVersion)"
    echo ""
    
    echo "User Verification Results:"
    echo "-------------------------"
    
    for user in "${USERS_TO_CHECK[@]}"; do
        if id -u "$user" >/dev/null 2>&1; then
            uid=$(id -u "$user")
            gid=$(id -g "$user")
            groups=$(id -Gn "$user")
            echo "✓ $user - EXISTS (UID: $uid, GID: $gid, Groups: $groups)"
        else
            echo "✗ $user - NOT FOUND"
        fi
    done
    
    echo ""
    echo "All Local Users:"
    echo "---------------"
    dscl . -list /Users UniqueID | awk '$2 >= 500 {print $1 " (UID: " $2 ")"}' | sort -n -k3
    
} > "$REPORT_FILE"

echo "Report generated: $REPORT_FILE"

Best Practices

1. Error Handling

Always include proper error handling in your scripts:

#!/bin/bash

# Robust user check with error handling
check_user() {
    local username="$1"
    
    if [ -z "$username" ]; then
        echo "ERROR: Username not provided" >&2
        return 1
    fi
    
    if id -u "$username" >/dev/null 2>&1; then
        echo "User '$username' exists"
        return 0
    else
        echo "User '$username' does not exist"
        return 1
    fi
}

# Usage
check_user "$1" || exit 1

2. Logging

Implement comprehensive logging:

#!/bin/bash

# User check with logging
LOG_FILE="/var/log/user_verification.log"

log_message() {
    echo "$(date '+%Y-%m-%d %H:%M:%S') - $1" >> "$LOG_FILE"
}

USERNAME="$1"
log_message "Starting user verification for: $USERNAME"

if id -u "$USERNAME" >/dev/null 2>&1; then
    log_message "SUCCESS: User $USERNAME exists"
    echo "User exists"
else
    log_message "INFO: User $USERNAME does not exist"
    echo "User does not exist"
fi

3. Security Considerations

  • Run scripts with minimal required privileges
  • Validate input to prevent injection attacks
  • Use secure methods for remote execution
  • Implement audit trails for compliance

Troubleshooting

Common Issues

  1. Permission Denied: Ensure the script has appropriate permissions and is run by a user with sufficient privileges
  2. Command Not Found: Verify that required commands (id, dscl) are available
  3. Network Issues: For remote verification, ensure SSH keys are properly configured
  4. Directory Service Issues: Check connectivity to domain controllers for network accounts

Debugging

Add debugging to your scripts:

#!/bin/bash

# Enable debugging
set -x

# Your script here
USERNAME="$1"
echo "Debug: Checking user $USERNAME"

if id -u "$USERNAME" >/dev/null 2>&1; then
    echo "Debug: User exists"
else
    echo "Debug: User does not exist"
fi

Compatibility Notes

  • macOS 10.14 and later: Full script compatibility
  • Earlier versions: Some dscl commands may have different syntax
  • Network accounts: May require additional configuration for directory services
  • Managed accounts: Consider Mobile Device Management (MDM) policies

Conclusion

Verifying user existence on macOS devices is a fundamental aspect of system administration and security management. The scripts provided in this guide offer various approaches from simple existence checks to comprehensive user auditing.

Regular user verification helps maintain security, ensures compliance, and provides valuable insights into your Mac fleet's user landscape. Implement these scripts as part of your regular maintenance routines to keep your macOS environment secure and well-managed.

Remember to test all scripts in a controlled environment before deploying them across your fleet, and always maintain proper backup and recovery procedures when making system changes.

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.