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.

Retrieve Network Information on macOS

Collect detailed network information from your MacFleet devices using command-line tools. This tutorial covers MAC address discovery, IP configuration, port monitoring, and network diagnostics for comprehensive fleet management.

Understanding macOS Network Information

macOS provides several command-line utilities for network information gathering:

  • networksetup - Hardware port and network configuration management
  • ifconfig - Network interface configuration and status
  • netstat - Network connections and port information
  • arp - Address Resolution Protocol table management
  • ipconfig - IP address and DHCP configuration

Retrieve MAC Addresses

List All Hardware Ports

#!/bin/bash

# Display all network hardware ports and their MAC addresses
networksetup -listallhardwareports

echo "Hardware port information retrieved successfully"

Get Specific Interface MAC Address

#!/bin/bash

# Get MAC address for specific interface (Wi-Fi)
echo "Wi-Fi Interface (en0) MAC Address:"
networksetup -getmacaddress en0

echo -e "\nEthernet Interface (en1) MAC Address:"
networksetup -getmacaddress en1

echo -e "\nThunderbolt Bridge (bridge0) MAC Address:"
networksetup -getmacaddress bridge0 2>/dev/null || echo "Thunderbolt Bridge not available"

Comprehensive MAC Address Report

#!/bin/bash

# Generate detailed MAC address report
echo "=== MacFleet Network Hardware Report ==="
echo "Device: $(hostname)"
echo "Date: $(date)"
echo "========================================="

# Get all hardware ports
echo -e "\n📡 Network Hardware Inventory:"
networksetup -listallhardwareports

echo -e "\n🔍 Primary Interface Details:"
echo "Wi-Fi (en0): $(networksetup -getmacaddress en0 | awk '{print $3}')"
echo "Ethernet (en1): $(networksetup -getmacaddress en1 | awk '{print $3}' 2>/dev/null || echo 'Not available')"

# Check for additional interfaces
echo -e "\n🌐 Additional Interfaces:"
for i in {2..5}; do
    mac_addr=$(networksetup -getmacaddress en$i 2>/dev/null | awk '{print $3}')
    if [[ -n "$mac_addr" && "$mac_addr" != "not" ]]; then
        echo "en$i: $mac_addr"
    fi
done

Discover IP Addresses

Basic IP Address Retrieval

#!/bin/bash

# Get IP address for Wi-Fi interface
WIFI_IP=$(ipconfig getifaddr en0 2>/dev/null)
ETHERNET_IP=$(ipconfig getifaddr en1 2>/dev/null)

echo "Network IP Addresses:"
echo "Wi-Fi (en0): ${WIFI_IP:-Not connected}"
echo "Ethernet (en1): ${ETHERNET_IP:-Not connected}"

Comprehensive IP Configuration

#!/bin/bash

# Detailed IP configuration report
echo "=== MacFleet IP Configuration Report ==="
echo "Device: $(hostname)"
echo "Timestamp: $(date)"
echo "========================================"

# Active network interfaces
echo -e "\n🌐 Active Network Interfaces:"
for interface in en0 en1 en2 en3; do
    ip_addr=$(ipconfig getifaddr $interface 2>/dev/null)
    if [[ -n "$ip_addr" ]]; then
        echo "$interface: $ip_addr"
        
        # Get additional details for active interfaces
        subnet_mask=$(ipconfig getoption $interface subnet_mask 2>/dev/null)
        router=$(ipconfig getoption $interface router 2>/dev/null)
        dns_servers=$(ipconfig getoption $interface domain_name_server 2>/dev/null)
        
        echo "  Subnet: ${subnet_mask:-N/A}"
        echo "  Gateway: ${router:-N/A}"
        echo "  DNS: ${dns_servers:-N/A}"
        echo ""
    fi
done

# Public IP address
echo "🌍 External IP Address:"
curl -s ifconfig.me 2>/dev/null || echo "Unable to retrieve external IP"

Network Interface Status

#!/bin/bash

# Monitor network interface status
echo "=== Network Interface Status Monitor ==="

# Get interface statistics
echo -e "\n📊 Interface Statistics:"
ifconfig | grep -E "(en[0-9]:|inet |status:|media:)" | while read line; do
    echo "$line"
done

echo -e "\n🔄 DHCP Lease Information:"
for interface in en0 en1; do
    lease_info=$(ipconfig getpacket $interface 2>/dev/null)
    if [[ -n "$lease_info" ]]; then
        echo "Interface $interface:"
        echo "$lease_info" | grep -E "(lease_time|server_identifier|domain_name)"
        echo ""
    fi
done

Analyze Network Configuration

Complete Network Overview

#!/bin/bash

# Comprehensive network configuration analysis
echo "=== Complete Network Overview ==="
ifconfig

echo -e "\n🔍 Network Summary:"
ifconfig | grep -E "^[a-z]" | while read line; do
    interface=$(echo $line | cut -d: -f1)
    status=$(ifconfig $interface | grep "status:" | cut -d' ' -f2-)
    echo "$interface: ${status:-active}"
done

Network Services and DNS

#!/bin/bash

# Network services and DNS configuration
echo "=== Network Services Configuration ==="

echo "🌐 DNS Configuration:"
echo "System DNS Servers:"
scutil --dns | grep "nameserver" | head -5

echo -e "\n📡 Network Services:"
networksetup -listallnetworkservices

echo -e "\n🔍 Active Network Service Details:"
active_service=$(networksetup -listallnetworkservices | grep -v "asterisk" | head -2 | tail -1)
if [[ -n "$active_service" ]]; then
    echo "Service: $active_service"
    networksetup -getinfo "$active_service"
fi

Subnet and Routing Information

#!/bin/bash

# Subnet mask and routing information
echo "=== Routing and Subnet Information ==="

echo "🛣️  Routing Table:"
netstat -rn | head -10

echo -e "\n🔍 Interface Subnet Details:"
for interface in en0 en1; do
    ip_addr=$(ipconfig getifaddr $interface 2>/dev/null)
    if [[ -n "$ip_addr" ]]; then
        subnet_mask=$(ipconfig getoption $interface subnet_mask 2>/dev/null)
        echo "$interface: $ip_addr/${subnet_mask:-unknown}"
    fi
done

Monitor Port Information

Active TCP Connections

#!/bin/bash

# Display active TCP connections
echo "=== Active TCP Connections ==="
netstat -ap TCP

echo -e "\n📊 Connection Summary:"
echo "Total connections: $(netstat -ap TCP | grep -c ESTABLISHED)"
echo "Listening ports: $(netstat -ap TCP | grep -c LISTEN)"
echo "Time-wait connections: $(netstat -ap TCP | grep -c TIME_WAIT)"

Listening Ports Analysis

#!/bin/bash

# Analyze listening ports
echo "=== Listening Ports Analysis ==="

echo "🔍 All Listening Ports:"
netstat -a | grep -i "LISTEN"

echo -e "\n📋 Listening Ports Summary:"
netstat -a | grep -i "LISTEN" | awk '{print $4}' | cut -d. -f2 | sort -n | uniq -c | sort -nr

echo -e "\n🔒 Security-Relevant Ports:"
netstat -a | grep -i "LISTEN" | grep -E ":(22|80|443|993|995|587|25|53|21|23) "

Port Monitoring Script

#!/bin/bash

# Comprehensive port monitoring
LOG_FILE="/var/log/macfleet_ports.log"

monitor_ports() {
    local timestamp=$(date '+%Y-%m-%d %H:%M:%S')
    
    {
        echo "=== Port Monitoring Report ==="
        echo "Timestamp: $timestamp"
        echo "Device: $(hostname)"
        echo "================================"
        
        echo -e "\n🔍 Current Listening Ports:"
        netstat -a | grep -i "LISTEN" | head -20
        
        echo -e "\n📊 Connection Statistics:"
        echo "ESTABLISHED: $(netstat -ap TCP | grep -c ESTABLISHED)"
        echo "LISTEN: $(netstat -ap TCP | grep -c LISTEN)"
        echo "TIME_WAIT: $(netstat -ap TCP | grep -c TIME_WAIT)"
        echo "CLOSE_WAIT: $(netstat -ap TCP | grep -c CLOSE_WAIT)"
        
        echo -e "\n🚨 Suspicious Connections:"
        netstat -ap TCP | grep -E ":(6667|6697|8080|9050|4444|31337)" || echo "None detected"
        
    } | tee -a "$LOG_FILE"
}

# Execute monitoring
monitor_ports

Display ARP Table

Basic ARP Information

#!/bin/bash

# Display Address Resolution Protocol table
arp -a

echo "ARP table retrieved successfully"

Detailed ARP Analysis

#!/bin/bash

# Comprehensive ARP table analysis
echo "=== ARP Table Analysis ==="
echo "Device: $(hostname)"
echo "Date: $(date)"
echo "=========================="

echo -e "\n🔍 Complete ARP Table:"
arp -a

echo -e "\n📊 ARP Statistics:"
total_entries=$(arp -a | wc -l)
incomplete_entries=$(arp -a | grep -c "incomplete")
complete_entries=$((total_entries - incomplete_entries))

echo "Total ARP entries: $total_entries"
echo "Complete entries: $complete_entries"
echo "Incomplete entries: $incomplete_entries"

echo -e "\n🌐 Network Neighbors:"
arp -a | head -10 | while read line; do
    hostname=$(echo $line | cut -d' ' -f1)
    ip=$(echo $line | cut -d'(' -f2 | cut -d')' -f1)
    mac=$(echo $line | cut -d' ' -f4)
    echo "$ip -> $mac ($hostname)"
done

ARP Security Check

#!/bin/bash

# ARP table security analysis
echo "=== ARP Security Analysis ==="

# Check for duplicate MAC addresses (potential ARP spoofing)
echo "🔒 Duplicate MAC Address Check:"
arp -a | awk '{print $4}' | sort | uniq -d | while read mac; do
    if [[ -n "$mac" ]]; then
        echo "⚠️  Duplicate MAC detected: $mac"
        arp -a | grep "$mac"
    fi
done

# Check for suspicious patterns
echo -e "\n🚨 Security Alerts:"
suspicious_count=$(arp -a | grep -c "incomplete")
if [[ $suspicious_count -gt 10 ]]; then
    echo "⚠️  High number of incomplete ARP entries: $suspicious_count"
fi

# Network vendor analysis
echo -e "\n🏢 Network Vendor Analysis:"
arp -a | grep -E "([0-9a-f]{2}:){5}[0-9a-f]{2}" | awk '{print $4}' | cut -d: -f1-3 | sort | uniq -c | sort -nr | head -5

Enterprise Network Monitoring Script

#!/bin/bash

# MacFleet Enterprise Network Monitoring Suite
LOG_FILE="/var/log/macfleet_network.log"
REPORT_FILE="/tmp/network_report_$(date +%Y%m%d_%H%M%S).txt"

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

# Generate comprehensive network report
generate_network_report() {
    {
        echo "MacFleet Network Assessment Report"
        echo "Generated: $(date)"
        echo "Device: $(hostname)"
        echo "User: $(whoami)"
        echo "OS Version: $(sw_vers -productVersion)"
        echo "=========================================="
        echo ""
        
        # Hardware inventory
        echo "🔧 Network Hardware:"
        networksetup -listallhardwareports
        echo ""
        
        # IP configuration
        echo "🌐 IP Configuration:"
        for interface in en0 en1 en2; do
            ip_addr=$(ipconfig getifaddr $interface 2>/dev/null)
            if [[ -n "$ip_addr" ]]; then
                echo "$interface: $ip_addr"
                mac_addr=$(networksetup -getmacaddress $interface | awk '{print $3}')
                echo "  MAC: $mac_addr"
                
                subnet=$(ipconfig getoption $interface subnet_mask 2>/dev/null)
                router=$(ipconfig getoption $interface router 2>/dev/null)
                echo "  Subnet: ${subnet:-N/A}"
                echo "  Gateway: ${router:-N/A}"
                echo ""
            fi
        done
        
        # Network services
        echo "📡 Network Services:"
        networksetup -listallnetworkservices | grep -v "asterisk"
        echo ""
        
        # DNS configuration
        echo "🔍 DNS Configuration:"
        scutil --dns | grep "nameserver" | head -3
        echo ""
        
        # Security assessment
        echo "🔒 Security Assessment:"
        listening_ports=$(netstat -a | grep -c "LISTEN")
        established_connections=$(netstat -ap TCP | grep -c ESTABLISHED)
        echo "Listening ports: $listening_ports"
        echo "Active connections: $established_connections"
        
        # Check for common security ports
        security_ports=$(netstat -a | grep -i "LISTEN" | grep -E ":(22|80|443|993|995)" | wc -l)
        echo "Security-relevant ports: $security_ports"
        
        echo ""
        echo "Report completed at: $(date)"
        
    } > "$REPORT_FILE"
    
    echo "📊 Network report generated: $REPORT_FILE"
}

# Network connectivity test
test_connectivity() {
    echo "=== Network Connectivity Test ==="
    
    # Test DNS resolution
    if nslookup google.com > /dev/null 2>&1; then
        echo "✅ DNS resolution: Working"
    else
        echo "❌ DNS resolution: Failed"
    fi
    
    # Test internet connectivity
    if ping -c 1 8.8.8.8 > /dev/null 2>&1; then
        echo "✅ Internet connectivity: Working"
    else
        echo "❌ Internet connectivity: Failed"
    fi
    
    # Test local gateway
    gateway=$(route -n get default | grep gateway | awk '{print $2}')
    if [[ -n "$gateway" ]] && ping -c 1 "$gateway" > /dev/null 2>&1; then
        echo "✅ Gateway connectivity: Working ($gateway)"
    else
        echo "❌ Gateway connectivity: Failed"
    fi
}

# Main execution
main() {
    log_action "=== MacFleet Network Monitoring Started ==="
    
    generate_network_report
    echo ""
    test_connectivity
    
    log_action "Network monitoring completed. Report: $REPORT_FILE"
}

# Execute main function
main "$@"

Network Information Reference

Common Network Interfaces

InterfaceDescriptionCommon Usage
en0Primary network interfaceWi-Fi connection
en1Secondary interfaceEthernet connection
en2-en5Additional interfacesUSB adapters, Thunderbolt
lo0Loopback interfaceLocal system communication
bridge0Thunderbolt bridgeDevice-to-device connections
utun0-utun3Tunnel interfacesVPN connections

Network Commands Quick Reference

# Get interface IP
ipconfig getifaddr en0

# Get interface configuration
ipconfig getoption en0 subnet_mask
ipconfig getoption en0 router
ipconfig getoption en0 domain_name_server

# Network hardware
networksetup -listallhardwareports
networksetup -getmacaddress en0

# Interface status
ifconfig en0
ifconfig -a

# Network connections
netstat -rn          # Routing table
netstat -i           # Interface statistics
netstat -ap TCP      # TCP connections

# ARP operations
arp -a               # Show ARP table
arp -d hostname      # Delete ARP entry

Advanced Network Diagnostics

Network Performance Testing

#!/bin/bash

# Network performance diagnostics
echo "=== Network Performance Diagnostics ==="

# Interface statistics
echo "📊 Interface Statistics:"
netstat -i

# Bandwidth monitoring
echo -e "\n🚀 Network Activity (10 seconds):"
if command -v nettop >/dev/null 2>&1; then
    timeout 10 nettop -l 1 -J bytes_in,bytes_out -P
else
    echo "nettop not available, using netstat"
    netstat -i
fi

# Latency testing
echo -e "\n⏱️  Latency Tests:"
echo "Google DNS (8.8.8.8):"
ping -c 3 8.8.8.8 | tail -1

echo "Cloudflare DNS (1.1.1.1):"
ping -c 3 1.1.1.1 | tail -1

Wireless Network Information

#!/bin/bash

# Wireless network detailed information
echo "=== Wireless Network Analysis ==="

# Current Wi-Fi information
current_wifi=$(networksetup -getairportnetwork en0)
echo "Current Wi-Fi: $current_wifi"

# Wi-Fi power status
wifi_power=$(networksetup -getairportpower en0)
echo "Wi-Fi Power: $wifi_power"

# Available networks (requires admin privileges)
echo -e "\n📡 Available Networks:"
if [[ $EUID -eq 0 ]]; then
    airport -s 2>/dev/null || echo "Airport utility not available"
else
    echo "Admin privileges required for network scanning"
fi

# Wi-Fi interface details
echo -e "\n🔍 Wi-Fi Interface Details:"
ifconfig en0 | grep -E "(inet|ether|status)"

Important Notes

  • Interface names may vary between macOS versions and hardware
  • Administrative privileges required for some network operations
  • Security implications - Monitor open ports and connections regularly
  • Performance impact - Network monitoring scripts may affect system performance
  • Privacy considerations - ARP tables contain information about network neighbors

Troubleshooting

Common Network Issues

No IP Address:

# Renew DHCP lease
sudo ipconfig set en0 DHCP

DNS Resolution Problems:

# Flush DNS cache
sudo dscacheutil -flushcache

Interface Not Responding:

# Reset network interface
sudo ifconfig en0 down
sudo ifconfig en0 up

Remember to test these scripts on individual devices before deploying across your MacFleet environment.

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.