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.

Configuring DNS Settings for Wi-Fi on Mac

The Domain Name System (DNS) is the backbone of the internet, converting human-readable domain names into IP addresses that enable seamless communication between devices. Proper DNS configuration can significantly impact your internet experience, affecting speed, security, and privacy. This comprehensive guide provides methods to configure DNS settings for Wi-Fi on macOS devices.

Understanding DNS and Its Importance

DNS servers act as translators between domain names (like google.com) and IP addresses (like 142.250.80.14). When you type a web address, your device queries a DNS server to find the corresponding IP address, then connects to that server.

Why Change DNS Settings?

There are several compelling reasons to modify your DNS configuration:

  • Improved Performance: Faster DNS servers can reduce website loading times
  • Enhanced Security: DNS filtering can block malicious websites and phishing attempts
  • Privacy Protection: Some DNS providers don't log your browsing activities
  • Content Access: Bypass geographical restrictions and censorship
  • Parental Controls: Filter inappropriate content for family networks
  • Ad Blocking: Some DNS services block advertisements at the DNS level

Popular DNS Providers

Before configuring DNS settings, consider these popular DNS providers:

Google Public DNS

  • Primary: 8.8.8.8
  • Secondary: 8.8.4.4
  • Features: Fast, reliable, minimal logging

Cloudflare DNS

  • Primary: 1.1.1.1
  • Secondary: 1.0.0.1
  • Features: Privacy-focused, very fast, security features

OpenDNS

  • Primary: 208.67.222.222
  • Secondary: 208.67.220.220
  • Features: Content filtering, malware protection

Quad9

  • Primary: 9.9.9.9
  • Secondary: 149.112.112.112
  • Features: Security-focused, blocks malicious domains

Prerequisites

Before configuring DNS settings, ensure you have:

  • Administrative privileges on the Mac
  • Terminal access or System Preferences access
  • Knowledge of your current network configuration
  • Backup of current DNS settings (optional but recommended)

Method 1: Using Shell Scripts

Basic DNS Configuration Script

This script configures DNS server settings for Wi-Fi on macOS:

#!/bin/bash

# Configure DNS servers for Wi-Fi
sudo networksetup -setdnsservers "Wi-Fi" 8.8.8.8 8.8.4.4

# Verify the configuration
output=$(networksetup -getdnsservers "Wi-Fi")
echo "Current DNS Servers: $output"

# Flush DNS cache
sudo dscacheutil -flushcache
echo "DNS cache flushed"

Advanced DNS Configuration Script

A more comprehensive script with multiple DNS options:

#!/bin/bash

# Advanced DNS configuration script for macOS Wi-Fi
# Usage: ./dns_config.sh [provider]
# Providers: google, cloudflare, opendns, quad9, reset

PROVIDER=${1:-google}
INTERFACE="Wi-Fi"

# Function to set DNS servers
set_dns_servers() {
    local primary=$1
    local secondary=$2
    local provider_name=$3
    
    echo "Setting DNS servers to $provider_name..."
    sudo networksetup -setdnsservers "$INTERFACE" "$primary" "$secondary"
    
    # Verify configuration
    current_dns=$(networksetup -getdnsservers "$INTERFACE")
    echo "Current DNS servers: $current_dns"
    
    # Flush DNS cache
    sudo dscacheutil -flushcache
    echo "DNS cache flushed"
    
    # Test DNS resolution
    echo "Testing DNS resolution..."
    nslookup google.com "$primary" | head -5
}

# Function to reset to automatic DNS
reset_dns() {
    echo "Resetting DNS to automatic (DHCP)..."
    sudo networksetup -setdnsservers "$INTERFACE" "Empty"
    current_dns=$(networksetup -getdnsservers "$INTERFACE")
    echo "Current DNS servers: $current_dns"
}

# Main configuration logic
case $PROVIDER in
    google)
        set_dns_servers "8.8.8.8" "8.8.4.4" "Google Public DNS"
        ;;
    cloudflare)
        set_dns_servers "1.1.1.1" "1.0.0.1" "Cloudflare DNS"
        ;;
    opendns)
        set_dns_servers "208.67.222.222" "208.67.220.220" "OpenDNS"
        ;;
    quad9)
        set_dns_servers "9.9.9.9" "149.112.112.112" "Quad9"
        ;;
    reset)
        reset_dns
        ;;
    *)
        echo "Usage: $0 [google|cloudflare|opendns|quad9|reset]"
        echo "Default: google"
        exit 1
        ;;
esac

echo "DNS configuration complete!"

Batch DNS Configuration for Multiple Macs

For managing DNS settings across multiple Mac devices:

#!/bin/bash

# Batch DNS configuration for multiple Macs
HOSTS=(
    "mac1.local"
    "mac2.local"
    "mac3.local"
)

DNS_PRIMARY="1.1.1.1"
DNS_SECONDARY="1.0.0.1"
INTERFACE="Wi-Fi"

echo "Configuring DNS on multiple Macs..."
echo "Primary DNS: $DNS_PRIMARY"
echo "Secondary DNS: $DNS_SECONDARY"
echo ""

for host in "${HOSTS[@]}"; do
    echo "Configuring $host..."
    
    if ping -c 1 -W 1000 "$host" >/dev/null 2>&1; then
        # Create script to run on remote host
        remote_script="sudo networksetup -setdnsservers '$INTERFACE' '$DNS_PRIMARY' '$DNS_SECONDARY' && sudo dscacheutil -flushcache"
        
        if ssh -o ConnectTimeout=5 -o BatchMode=yes "$host" "$remote_script" 2>/dev/null; then
            echo "  ✓ $host - DNS configured successfully"
        else
            echo "  ✗ $host - Failed to configure DNS"
        fi
    else
        echo "  ✗ $host - Host unreachable"
    fi
done

echo ""
echo "Batch DNS configuration complete!"

Method 2: Manual Configuration via System Preferences

Step-by-Step GUI Configuration

  1. Open System Preferences

    • Click the Apple menu > System Preferences
    • Or use Spotlight: Press Cmd+Space, type "System Preferences"
  2. Access Network Settings

    • Click on "Network"
    • Select "Wi-Fi" from the left sidebar
    • Click "Advanced..." button
  3. Configure DNS

    • Click the "DNS" tab
    • Click the "+" button to add DNS servers
    • Enter your preferred DNS servers (e.g., 1.1.1.1, 1.0.0.1)
    • Drag servers to reorder them by priority
  4. Apply Settings

    • Click "OK" to close the Advanced window
    • Click "Apply" to save changes

Command Line Verification

After manual configuration, verify settings using Terminal:

# Check current DNS servers
networksetup -getdnsservers "Wi-Fi"

# Test DNS resolution
nslookup google.com
dig google.com

# Check DNS response time
time nslookup google.com

DNS Management Scripts

Current DNS Information Script

Script to gather comprehensive DNS information:

#!/bin/bash

# DNS Information Gathering Script
echo "DNS Configuration Report"
echo "======================="
echo "Date: $(date)"
echo "Hostname: $(hostname)"
echo ""

# Get all network interfaces
interfaces=$(networksetup -listallnetworkservices | grep -v "denotes")

echo "Network Interfaces and DNS Settings:"
echo "-----------------------------------"

while IFS= read -r interface; do
    if [[ "$interface" != "" ]]; then
        echo "Interface: $interface"
        dns_servers=$(networksetup -getdnsservers "$interface")
        
        if [[ "$dns_servers" == "There aren't any DNS Servers set on"* ]]; then
            echo "  DNS: Automatic (DHCP)"
        else
            echo "  DNS Servers:"
            echo "$dns_servers" | while read -r server; do
                echo "    - $server"
            done
        fi
        echo ""
    fi
done <<< "$interfaces"

# Test DNS resolution performance
echo "DNS Resolution Test:"
echo "-------------------"
test_domains=("google.com" "cloudflare.com" "github.com")

for domain in "${test_domains[@]}"; do
    echo "Testing $domain..."
    time_result=$(time (nslookup "$domain" >/dev/null 2>&1) 2>&1 | grep real | awk '{print $2}')
    echo "  Resolution time: $time_result"
done

DNS Backup and Restore Script

#!/bin/bash

# DNS Backup and Restore Script
BACKUP_DIR="$HOME/dns_backups"
BACKUP_FILE="$BACKUP_DIR/dns_backup_$(date +%Y%m%d_%H%M%S).txt"

# Create backup directory
mkdir -p "$BACKUP_DIR"

# Function to backup DNS settings
backup_dns() {
    echo "Backing up DNS settings..."
    
    {
        echo "DNS Backup - $(date)"
        echo "======================"
        echo ""
        
        # Get all network interfaces
        interfaces=$(networksetup -listallnetworkservices | grep -v "denotes")
        
        while IFS= read -r interface; do
            if [[ "$interface" != "" ]]; then
                echo "Interface: $interface"
                networksetup -getdnsservers "$interface"
                echo ""
            fi
        done <<< "$interfaces"
        
    } > "$BACKUP_FILE"
    
    echo "DNS settings backed up to: $BACKUP_FILE"
}

# Function to restore DNS settings
restore_dns() {
    local backup_file=$1
    
    if [[ ! -f "$backup_file" ]]; then
        echo "Backup file not found: $backup_file"
        return 1
    fi
    
    echo "Restoring DNS settings from: $backup_file"
    echo "Note: Manual restoration required - backup file contains configuration for reference"
    cat "$backup_file"
}

# Main script logic
case "${1:-backup}" in
    backup)
        backup_dns
        ;;
    restore)
        restore_dns "$2"
        ;;
    list)
        echo "Available backups:"
        ls -la "$BACKUP_DIR"
        ;;
    *)
        echo "Usage: $0 [backup|restore <file>|list]"
        exit 1
        ;;
esac

Troubleshooting DNS Issues

Common DNS Problems and Solutions

  1. Slow Internet Browsing

    # Test DNS response times
    time nslookup google.com 8.8.8.8
    time nslookup google.com 1.1.1.1
    
    # Switch to faster DNS server
    sudo networksetup -setdnsservers "Wi-Fi" 1.1.1.1 1.0.0.1
  2. Unable to Access Certain Websites

    # Check if DNS is resolving the domain
    nslookup problematic-site.com
    
    # Try different DNS server
    nslookup problematic-site.com 8.8.8.8
  3. DNS Cache Issues

    # Flush DNS cache
    sudo dscacheutil -flushcache
    sudo killall -HUP mDNSResponder

DNS Diagnostic Script

#!/bin/bash

# DNS Diagnostic Script
echo "DNS Diagnostic Report"
echo "===================="
echo "Date: $(date)"
echo ""

# Check current DNS configuration
echo "1. Current DNS Configuration:"
echo "----------------------------"
networksetup -getdnsservers "Wi-Fi"
echo ""

# Test connectivity to common DNS servers
echo "2. DNS Server Connectivity Test:"
echo "--------------------------------"
dns_servers=("8.8.8.8" "1.1.1.1" "208.67.222.222" "9.9.9.9")

for server in "${dns_servers[@]}"; do
    if ping -c 1 -W 1000 "$server" >/dev/null 2>&1; then
        echo "✓ $server - Reachable"
    else
        echo "✗ $server - Unreachable"
    fi
done
echo ""

# Test DNS resolution
echo "3. DNS Resolution Test:"
echo "----------------------"
test_domains=("google.com" "cloudflare.com" "github.com")

for domain in "${test_domains[@]}"; do
    if nslookup "$domain" >/dev/null 2>&1; then
        echo "✓ $domain - Resolves correctly"
    else
        echo "✗ $domain - Resolution failed"
    fi
done
echo ""

# Check for DNS leaks
echo "4. DNS Leak Check:"
echo "-----------------"
echo "Current DNS resolver:"
nslookup myip.opendns.com resolver1.opendns.com | grep "Address" | tail -1
echo ""

echo "Diagnostic complete!"

Best Practices for DNS Configuration

1. Security Considerations

  • Use reputable DNS providers with security features
  • Regularly update DNS settings based on threat intelligence
  • Consider DNS-over-HTTPS (DoH) for enhanced privacy
  • Monitor DNS queries for suspicious activity

2. Performance Optimization

  • Test multiple DNS providers to find the fastest for your location
  • Use primary and secondary DNS servers for redundancy
  • Consider geographic proximity when selecting DNS servers
  • Monitor DNS resolution times regularly

3. Enterprise Management

  • Standardize DNS settings across all organizational devices
  • Document DNS configurations for disaster recovery
  • Implement DNS filtering for security and compliance
  • Use automated scripts for bulk configuration changes

4. Backup and Recovery

  • Always backup current DNS settings before making changes
  • Test new DNS configurations in a controlled environment
  • Have a rollback plan for DNS changes
  • Document all DNS configuration changes

Advanced DNS Configuration

DNS-over-HTTPS (DoH) Configuration

For enhanced privacy, configure DNS-over-HTTPS:

#!/bin/bash

# Configure DNS-over-HTTPS (DoH) on macOS
# Note: This requires macOS 11.0 or later

# Enable DoH with Cloudflare
sudo networksetup -setdnsservers "Wi-Fi" 1.1.1.1 1.0.0.1
sudo defaults write /Library/Preferences/com.apple.networkd.plist DoHServers -dict-add "1.1.1.1" "https://cloudflare-dns.com/dns-query"
sudo defaults write /Library/Preferences/com.apple.networkd.plist DoHServers -dict-add "1.0.0.1" "https://cloudflare-dns.com/dns-query"

# Restart network services
sudo launchctl unload /System/Library/LaunchDaemons/com.apple.networkd.plist
sudo launchctl load /System/Library/LaunchDaemons/com.apple.networkd.plist

echo "DNS-over-HTTPS configured with Cloudflare"

Custom DNS Configuration for Specific Domains

#!/bin/bash

# Configure custom DNS for specific domains
# Uses /etc/resolver for domain-specific DNS

# Create resolver directory
sudo mkdir -p /etc/resolver

# Configure specific domain to use custom DNS
echo "nameserver 8.8.8.8" | sudo tee /etc/resolver/company.local
echo "nameserver 8.8.4.4" | sudo tee -a /etc/resolver/company.local

# Flush DNS cache
sudo dscacheutil -flushcache
sudo killall -HUP mDNSResponder

echo "Custom DNS configured for company.local domain"

Monitoring and Maintenance

DNS Monitoring Script

#!/bin/bash

# DNS Monitoring Script
LOG_FILE="/var/log/dns_monitor.log"

# Function to log with timestamp
log_message() {
    echo "$(date '+%Y-%m-%d %H:%M:%S') - $1" | tee -a "$LOG_FILE"
}

# Monitor DNS performance
monitor_dns() {
    local dns_server=$1
    local test_domain=$2
    
    start_time=$(date +%s%N)
    if nslookup "$test_domain" "$dns_server" >/dev/null 2>&1; then
        end_time=$(date +%s%N)
        duration=$((($end_time - $start_time) / 1000000))
        log_message "DNS $dns_server: $test_domain resolved in ${duration}ms"
    else
        log_message "DNS $dns_server: Failed to resolve $test_domain"
    fi
}

# Monitor multiple DNS servers
dns_servers=("8.8.8.8" "1.1.1.1" "208.67.222.222")
test_domain="google.com"

log_message "Starting DNS monitoring"

for server in "${dns_servers[@]}"; do
    monitor_dns "$server" "$test_domain"
done

log_message "DNS monitoring complete"

Conclusion

Proper DNS configuration is crucial for optimal internet performance, security, and privacy. The scripts and methods provided in this guide offer comprehensive solutions for managing DNS settings on macOS devices, from simple configurations to advanced enterprise deployments.

Key takeaways:

  • Choose DNS providers that align with your performance and privacy requirements
  • Regularly test and monitor DNS performance
  • Implement proper backup and recovery procedures
  • Consider security implications of DNS configuration
  • Use automation for large-scale deployments

Remember to test any DNS changes in a controlled environment before deploying them across your Mac fleet. Proper DNS management can significantly improve your network experience while enhancing security and privacy.

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.