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.

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

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.