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.

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

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.