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.

Manage Badge Notifications on macOS

Control and manage badge notifications across your MacFleet devices using command-line tools. This tutorial covers removing badge notifications for specific apps, managing dock-wide notifications, and implementing enterprise notification policies.

Understanding Badge Notifications

Badge notifications are the red circular icons that appear above application icons in the macOS dock, typically displaying numbers to indicate unread items like emails, messages, or updates. While useful for individual users, enterprise environments often require centralized notification management.

Key Features

  • App-specific control - Remove badges from individual applications
  • Dock-wide management - Clear all badge notifications at once
  • Automatic restoration - Badges reappear when applications are opened
  • System preference integration - Works with macOS notification settings

Remove Badge Notifications for Specific Apps

Basic Badge Removal

#!/bin/bash

# Remove badge notification for a specific application
APP_NAME="Mail"

defaults write com.apple.systempreferences AttentionPrefBundleIDs 0 && killall "$APP_NAME"

echo "Badge notification removed for $APP_NAME"

Enhanced App Badge Management

#!/bin/bash

# Advanced badge notification removal with validation
remove_app_badge() {
    local app_name="$1"
    
    if [[ -z "$app_name" ]]; then
        echo "❌ Error: Application name required"
        return 1
    fi
    
    # Check if application is running
    if pgrep -x "$app_name" > /dev/null; then
        echo "📱 Removing badge notification for $app_name..."
        
        # Remove badge notification
        defaults write com.apple.systempreferences AttentionPrefBundleIDs 0
        
        # Terminate and restart application to apply changes
        if killall "$app_name" 2>/dev/null; then
            echo "✅ Badge notification removed for $app_name"
            echo "ℹ️  Note: Badge will reappear when $app_name is reopened"
        else
            echo "⚠️  Warning: Could not restart $app_name (may not be running)"
        fi
    else
        echo "ℹ️  $app_name is not currently running"
        defaults write com.apple.systempreferences AttentionPrefBundleIDs 0
        echo "✅ Badge notification setting updated for $app_name"
    fi
}

# Usage examples
remove_app_badge "Mail"
remove_app_badge "Messages"
remove_app_badge "Calendar"

Common Applications Badge Removal

#!/bin/bash

# Remove badge notifications for common enterprise applications
COMMON_APPS=("Mail" "Messages" "Calendar" "Reminders" "FaceTime" "App Store" "System Preferences")

echo "🧹 Removing badge notifications for common applications..."

for app in "${COMMON_APPS[@]}"; do
    echo "Processing $app..."
    
    # Set notification preference
    defaults write com.apple.systempreferences AttentionPrefBundleIDs 0
    
    # Kill application if running
    if pgrep -x "$app" > /dev/null; then
        killall "$app" 2>/dev/null
        echo "  ✅ Badge cleared for $app"
    else
        echo "  ⏭️  $app not running, preference updated"
    fi
done

echo "🎉 Badge notification cleanup completed"

Remove All Badge Notifications (Dock-wide)

Basic Dock Badge Clearing

#!/bin/bash

# Remove all badge notifications from the dock
defaults write com.apple.systempreferences AttentionPrefBundleIDs 0 && killall Dock

echo "All badge notifications cleared from dock"

Comprehensive Dock Management

#!/bin/bash

# Advanced dock badge notification management
clear_all_dock_badges() {
    echo "🏗️  Clearing all badge notifications from dock..."
    
    # Backup current dock preferences
    local backup_file="/tmp/dock_backup_$(date +%s).plist"
    defaults export com.apple.dock "$backup_file"
    echo "📋 Dock preferences backed up to: $backup_file"
    
    # Clear badge notifications
    defaults write com.apple.systempreferences AttentionPrefBundleIDs 0
    
    # Get list of running dock applications
    local dock_apps
    dock_apps=$(osascript -e 'tell application "System Events" to get name of every application process whose background only is false')
    
    echo "🔄 Restarting dock to apply changes..."
    killall Dock
    
    # Wait for dock to restart
    sleep 3
    
    echo "✅ All badge notifications cleared from dock"
    echo "ℹ️  Badges will reappear when applications receive new notifications"
    
    return 0
}

# Execute dock badge clearing
clear_all_dock_badges

Enterprise Badge Management Script

#!/bin/bash

# MacFleet Badge Notification Management Tool
# Centralized control of badge notifications across enterprise devices

# Configuration
LOG_FILE="/var/log/macfleet_badges.log"
CONFIG_FILE="/etc/macfleet/badge_policy.conf"
BACKUP_DIR="/var/backups/macfleet/badges"

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

# Create necessary directories
setup_directories() {
    sudo mkdir -p "$(dirname "$LOG_FILE")" 2>/dev/null
    sudo mkdir -p "$BACKUP_DIR" 2>/dev/null
    sudo mkdir -p "$(dirname "$CONFIG_FILE")" 2>/dev/null
}

# Load configuration
load_config() {
    if [[ -f "$CONFIG_FILE" ]]; then
        source "$CONFIG_FILE"
        log_action "Configuration loaded from $CONFIG_FILE"
    else
        # Default configuration
        BADGE_POLICY="disabled"  # Options: enabled, disabled, selective
        ALLOWED_BADGE_APPS=("Calendar" "Reminders")
        BLOCKED_BADGE_APPS=("App Store" "System Preferences")
        AUTO_CLEAR_INTERVAL=3600  # 1 hour
        
        log_action "Using default configuration"
    fi
}

# Backup current badge settings
backup_badge_settings() {
    local backup_file="$BACKUP_DIR/badge_settings_$(date +%Y%m%d_%H%M%S).plist"
    
    defaults export com.apple.systempreferences "$backup_file" 2>/dev/null
    
    if [[ -f "$backup_file" ]]; then
        log_action "Badge settings backed up to: $backup_file"
        echo "$backup_file"
    else
        log_action "Warning: Could not backup badge settings"
        return 1
    fi
}

# Get current badge status
get_badge_status() {
    echo "📊 Current Badge Notification Status:"
    echo "======================================"
    
    # Check system preferences setting
    local attention_pref
    attention_pref=$(defaults read com.apple.systempreferences AttentionPrefBundleIDs 2>/dev/null || echo "not set")
    echo "System AttentionPrefBundleIDs: $attention_pref"
    
    # List applications with potential badges
    echo -e "\n📱 Applications that may show badges:"
    local badge_apps=("Mail" "Messages" "Calendar" "Reminders" "FaceTime" "App Store" "System Preferences" "Contacts")
    
    for app in "${badge_apps[@]}"; do
        if pgrep -x "$app" > /dev/null; then
            echo "  🟢 $app (running)"
        else
            echo "  ⚪ $app (not running)"
        fi
    done
    
    # Check dock processes
    echo -e "\n🏗️  Dock status:"
    if pgrep -x "Dock" > /dev/null; then
        echo "  🟢 Dock is running"
    else
        echo "  🔴 Dock is not running"
    fi
}

# Apply badge policy
apply_badge_policy() {
    log_action "Applying badge policy: $BADGE_POLICY"
    
    case "$BADGE_POLICY" in
        "disabled")
            disable_all_badges
            ;;
        "enabled")
            enable_all_badges
            ;;
        "selective")
            apply_selective_policy
            ;;
        *)
            log_action "Error: Unknown badge policy: $BADGE_POLICY"
            return 1
            ;;
    esac
}

# Disable all badge notifications
disable_all_badges() {
    echo "🚫 Disabling all badge notifications..."
    
    backup_badge_settings
    
    # Set system preference to disable badges
    defaults write com.apple.systempreferences AttentionPrefBundleIDs 0
    
    # Restart dock to apply changes
    killall Dock 2>/dev/null
    
    log_action "All badge notifications disabled"
    echo "✅ All badge notifications have been disabled"
}

# Enable all badge notifications
enable_all_badges() {
    echo "✅ Enabling all badge notifications..."
    
    backup_badge_settings
    
    # Remove the restriction (delete the key)
    defaults delete com.apple.systempreferences AttentionPrefBundleIDs 2>/dev/null
    
    # Restart dock to apply changes
    killall Dock 2>/dev/null
    
    log_action "All badge notifications enabled"
    echo "✅ All badge notifications have been enabled"
}

# Apply selective badge policy
apply_selective_policy() {
    echo "🎯 Applying selective badge policy..."
    
    # For selective policy, we need to manage individual app notifications
    # This requires more complex notification management
    
    for app in "${BLOCKED_BADGE_APPS[@]}"; do
        echo "  🚫 Blocking badges for $app"
        # Kill app to clear current badge
        killall "$app" 2>/dev/null
    done
    
    # Set system preference
    defaults write com.apple.systempreferences AttentionPrefBundleIDs 0
    
    log_action "Selective badge policy applied"
    echo "✅ Selective badge policy has been applied"
}

# Monitor and auto-clear badges
monitor_badges() {
    echo "👁️  Starting badge monitoring (interval: ${AUTO_CLEAR_INTERVAL}s)..."
    
    while true; do
        if [[ "$BADGE_POLICY" == "disabled" ]]; then
            # Clear any badges that may have appeared
            defaults write com.apple.systempreferences AttentionPrefBundleIDs 0
            log_action "Auto-cleared badges during monitoring"
        fi
        
        sleep "$AUTO_CLEAR_INTERVAL"
    done
}

# Generate badge management report
generate_report() {
    local report_file="/tmp/macfleet_badge_report_$(date +%Y%m%d_%H%M%S).txt"
    
    {
        echo "MacFleet Badge Notification Report"
        echo "=================================="
        echo "Generated: $(date)"
        echo "Hostname: $(hostname)"
        echo "Policy: $BADGE_POLICY"
        echo ""
        
        echo "System Configuration:"
        echo "  AttentionPrefBundleIDs: $(defaults read com.apple.systempreferences AttentionPrefBundleIDs 2>/dev/null || echo 'not set')"
        echo ""
        
        echo "Application Status:"
        local apps=("Mail" "Messages" "Calendar" "Reminders" "App Store")
        for app in "${apps[@]}"; do
            if pgrep -x "$app" > /dev/null; then
                echo "  $app: Running"
            else
                echo "  $app: Not running"
            fi
        done
        
        echo ""
        echo "Recent Actions:"
        tail -10 "$LOG_FILE" 2>/dev/null || echo "No recent log entries"
        
    } > "$report_file"
    
    echo "📄 Badge management report generated: $report_file"
    log_action "Report generated: $report_file"
}

# Main function
main() {
    case "${1:-status}" in
        "disable")
            setup_directories
            load_config
            log_action "=== Badge Management: Disable All ==="
            disable_all_badges
            ;;
        "enable")
            setup_directories
            load_config
            log_action "=== Badge Management: Enable All ==="
            enable_all_badges
            ;;
        "policy")
            setup_directories
            load_config
            log_action "=== Badge Management: Apply Policy ==="
            apply_badge_policy
            ;;
        "monitor")
            setup_directories
            load_config
            log_action "=== Badge Management: Start Monitoring ==="
            monitor_badges
            ;;
        "report")
            setup_directories
            load_config
            generate_report
            ;;
        "status"|*)
            setup_directories
            load_config
            get_badge_status
            ;;
    esac
}

# Execute main function with parameters
main "$@"

Badge Notification Management Commands

Quick Reference

TaskCommand
Remove specific app badgedefaults write com.apple.systempreferences AttentionPrefBundleIDs 0 && killall AppName
Clear all dock badgesdefaults write com.apple.systempreferences AttentionPrefBundleIDs 0 && killall Dock
Check current settingdefaults read com.apple.systempreferences AttentionPrefBundleIDs
Reset to defaultdefaults delete com.apple.systempreferences AttentionPrefBundleIDs

Application-Specific Examples

# Common applications
defaults write com.apple.systempreferences AttentionPrefBundleIDs 0 && killall Mail
defaults write com.apple.systempreferences AttentionPrefBundleIDs 0 && killall Messages
defaults write com.apple.systempreferences AttentionPrefBundleIDs 0 && killall "App Store"
defaults write com.apple.systempreferences AttentionPrefBundleIDs 0 && killall Calendar

Troubleshooting

Common Issues

  1. Badges reappear after clearing

    • This is normal behavior; badges return when apps receive new notifications
    • Use monitoring scripts for persistent clearing
  2. Application won't restart

    • Some apps may need manual restart
    • Check if app is set to launch at login
  3. Dock doesn't update

    • Try forcing dock restart: killall Dock && sleep 2 && open /System/Library/CoreServices/Dock.app

Verification Commands

# Check if setting was applied
defaults read com.apple.systempreferences AttentionPrefBundleIDs

# List running applications
ps aux | grep -E "(Mail|Messages|Calendar)" | grep -v grep

# Monitor dock process
ps aux | grep Dock | grep -v grep

Important Notes

  • Temporary effect: Badge notifications will reappear when applications receive new notifications
  • System restart: Settings persist across system restarts
  • User experience: Consider user notification needs before enterprise-wide deployment
  • Application behavior: Some apps may require manual restart to apply changes
  • Testing recommended: Test on individual devices before fleet-wide deployment

Enterprise Deployment

For enterprise deployment, consider:

  1. Policy configuration - Define which applications should show badges
  2. User communication - Inform users about notification changes
  3. Monitoring setup - Implement automated badge clearing if required
  4. Backup procedures - Save original settings before making changes
  5. Rollback plan - Ability to restore original notification behavior

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.