# ================================================================================ # SCRIPT COMPLETO MIKROTIK - LOAD BALANCE + HOTSPOT SOCIAL # ================================================================================ # Configuração: 3 WANs com Load Balance/Failover + Hotspot Social na ETH5 # Gateways: 192.168.0.1, 192.168.1.1, 192.168.2.1 # Autor: Configuração Personalizada # Data: $(date '+%d/%m/%Y %H:%M:%S') # ================================================================================ # ============================ # AGUARDAR E PREPARAR SISTEMA # ============================ :log info "=== INICIANDO CONFIGURAÇÃO COMPLETA ===" :log info "Aguardando sistema estabilizar..." :delay 3s # ============================ # CONFIGURAÇÕES BÁSICAS DO SISTEMA # ============================ :log info "Configurando sistema básico..." # Nome do roteador /system identity set name="MikroTik-LoadBalance-Hotspot" # Configuração de tempo /system clock set time-zone-name=America/Sao_Paulo /system ntp client set enabled=yes server-dns-names=pool.ntp.br # ============================ # LIMPEZA DE CONFIGURAÇÕES ANTIGAS # ============================ :log info "Limpando configurações antigas..." # Remover hotspots existentes :foreach i in=[/ip hotspot find] do={/ip hotspot remove $i} :foreach i in=[/ip hotspot profile find name!="default"] do={/ip hotspot profile remove $i} :foreach i in=[/ip hotspot user profile find name!="default"] do={/ip hotspot user profile remove $i} # Remover DHCP servers existentes (exceto padrões) :foreach i in=[/ip dhcp-server find] do={/ip dhcp-server remove $i} # Remover pools existentes :foreach i in=[/ip pool find] do={/ip pool remove $i} # Limpar mangle e NAT :foreach i in=[/ip firewall mangle find] do={/ip firewall mangle remove $i} :foreach i in=[/ip firewall nat find] do={/ip firewall nat remove $i} # Limpar rotas dinâmicas :foreach i in=[/ip route find dst-address="0.0.0.0/0"] do={/ip route remove $i} :delay 2s # ============================ # CONFIGURAÇÃO DAS INTERFACES # ============================ :log info "Configurando interfaces de rede..." # Renomear interfaces /interface ethernet set ether1 name=wan1 /interface ethernet set ether2 name=wan2 /interface ethernet set ether3 name=wan3 /interface ethernet set ether4 name=lan /interface ethernet set ether5 name=hotspot-eth # Remover IPs existentes das interfaces :foreach i in=[/ip address find interface=wan1] do={/ip address remove $i} :foreach i in=[/ip address find interface=wan2] do={/ip address remove $i} :foreach i in=[/ip address find interface=wan3] do={/ip address remove $i} :foreach i in=[/ip address find interface=lan] do={/ip address remove $i} :foreach i in=[/ip address find interface=hotspot-eth] do={/ip address remove $i} :delay 1s # Configurar IPs das WANs /ip address add address=192.168.0.100/24 interface=wan1 comment="WAN1" /ip address add address=192.168.1.100/24 interface=wan2 comment="WAN2" /ip address add address=192.168.2.100/24 interface=wan3 comment="WAN3" # Configurar LAN e Hotspot /ip address add address=10.0.0.1/24 interface=lan comment="LAN-Principal" /ip address add address=192.168.100.1/24 interface=hotspot-eth comment="Hotspot" # ============================ # CONFIGURAÇÃO DNS # ============================ :log info "Configurando DNS..." /ip dns set servers=8.8.8.8,8.8.4.4,1.1.1.1 allow-remote-requests=yes cache-size=4096KiB # ============================ # CONFIGURAÇÃO DOS POOLS DE IP # ============================ :log info "Criando pools de IP..." # Pool para LAN /ip pool add name=lan-pool ranges=10.0.0.10-10.0.0.100 comment="Pool-LAN" # Pool para Hotspot /ip pool add name=hotspot-pool ranges=192.168.100.10-192.168.100.200 comment="Pool-Hotspot" # ============================ # CONFIGURAÇÃO DHCP # ============================ :log info "Configurando servidores DHCP..." # DHCP LAN /ip dhcp-server network add address=10.0.0.0/24 gateway=10.0.0.1 dns-server=10.0.0.1 comment="Network-LAN" /ip dhcp-server add name=lan-dhcp interface=lan address-pool=lan-pool lease-time=1d disabled=no comment="DHCP-LAN" # DHCP Hotspot /ip dhcp-server network add address=192.168.100.0/24 gateway=192.168.100.1 dns-server=192.168.100.1 comment="Network-Hotspot" /ip dhcp-server add name=hotspot-dhcp interface=hotspot-eth address-pool=hotspot-pool lease-time=2h disabled=no comment="DHCP-Hotspot" # ============================ # CONFIGURAÇÃO DE ROTEAMENTO # ============================ :log info "Configurando tabelas de roteamento..." # Criar tabelas de roteamento /routing table add name=wan1_table fib comment="Tabela-WAN1" /routing table add name=wan2_table fib comment="Tabela-WAN2" /routing table add name=wan3_table fib comment="Tabela-WAN3" :delay 1s # Rotas nas tabelas específicas /ip route add dst-address=0.0.0.0/0 gateway=192.168.0.1 routing-table=wan1_table distance=1 comment="Route-WAN1-Table" /ip route add dst-address=0.0.0.0/0 gateway=192.168.1.1 routing-table=wan2_table distance=1 comment="Route-WAN2-Table" /ip route add dst-address=0.0.0.0/0 gateway=192.168.2.1 routing-table=wan3_table distance=1 comment="Route-WAN3-Table" # Rotas principais para failover /ip route add dst-address=0.0.0.0/0 gateway=192.168.0.1 distance=1 check-gateway=ping comment="Main-WAN1" /ip route add dst-address=0.0.0.0/0 gateway=192.168.1.1 distance=2 check-gateway=ping comment="Backup-WAN2" /ip route add dst-address=0.0.0.0/0 gateway=192.168.2.1 distance=3 check-gateway=ping comment="Backup-WAN3" # ============================ # CONFIGURAÇÃO LOAD BALANCE # ============================ :log info "Configurando load balance..." # Mangle para load balance /ip firewall mangle add chain=prerouting in-interface=lan connection-mark=no-mark \ dst-address-type=!local per-connection-classifier=both-addresses:3/0 \ action=mark-connection new-connection-mark=wan1_conn comment="LB-Mark-WAN1" /ip firewall mangle add chain=prerouting in-interface=lan connection-mark=no-mark \ dst-address-type=!local per-connection-classifier=both-addresses:3/1 \ action=mark-connection new-connection-mark=wan2_conn comment="LB-Mark-WAN2" /ip firewall mangle add chain=prerouting in-interface=lan connection-mark=no-mark \ dst-address-type=!local per-connection-classifier=both-addresses:3/2 \ action=mark-connection new-connection-mark=wan3_conn comment="LB-Mark-WAN3" # Mangle para roteamento /ip firewall mangle add chain=prerouting connection-mark=wan1_conn \ action=mark-routing new-routing-mark=wan1_table comment="LB-Route-WAN1" /ip firewall mangle add chain=prerouting connection-mark=wan2_conn \ action=mark-routing new-routing-mark=wan2_table comment="LB-Route-WAN2" /ip firewall mangle add chain=prerouting connection-mark=wan3_conn \ action=mark-routing new-routing-mark=wan3_table comment="LB-Route-WAN3" # ============================ # CONFIGURAÇÃO NAT # ============================ :log info "Configurando NAT..." # NAT para todas as WANs /ip firewall nat add chain=srcnat out-interface=wan1 action=masquerade comment="NAT-WAN1" /ip firewall nat add chain=srcnat out-interface=wan2 action=masquerade comment="NAT-WAN2" /ip firewall nat add chain=srcnat out-interface=wan3 action=masquerade comment="NAT-WAN3" # ============================ # CONFIGURAÇÃO DO HOTSPOT # ============================ :log info "Configurando hotspot social..." # 1. Perfil do usuário hotspot /ip hotspot user profile add name=perfil-usuario \ session-timeout=4h \ idle-timeout=30m \ keepalive-timeout=2m \ status-autorefresh=1m \ shared-users=1 \ rate-limit=50M/50M \ transparent-proxy=yes \ comment="Perfil-Usuario-Hotspot" # 2. Perfil do servidor hotspot /ip hotspot profile add name=perfil-servidor \ hotspot-address=192.168.100.1 \ dns-name=login.wifi \ html-directory=hotspot \ http-proxy=0.0.0.0:0 \ login-by=email,http-chap \ use-radius=no \ mac-auth-mode=no \ trial-uptime-limit=4h \ trial-user-profile=perfil-usuario \ smtp-server=0.0.0.0:0 \ split-user-domain=no \ comment="Perfil-Servidor-Hotspot" :delay 2s # 3. Criar servidor hotspot /ip hotspot add name=servidor-hotspot interface=hotspot-eth address-pool=hotspot-pool \ profile=perfil-servidor disabled=no comment="Servidor-Hotspot-Principal" # 4. Usuários do hotspot /ip hotspot user add name=T-trial password="" profile=perfil-usuario limit-uptime=4h \ disabled=no comment="Usuario-Trial-Email" /ip hotspot user add name=admin password=123456 profile=perfil-usuario \ disabled=no comment="Usuario-Admin" # ============================ # CONFIGURAÇÃO FIREWALL # ============================ :log info "Configurando firewall..." # Firewall Filter /ip firewall filter add chain=input action=accept connection-state=established,related comment="Accept-Established" /ip firewall filter add chain=input action=accept src-address=10.0.0.0/24 comment="Accept-LAN" /ip firewall filter add chain=input action=accept src-address=192.168.100.0/24 comment="Accept-Hotspot" /ip firewall filter add chain=input action=accept protocol=icmp comment="Accept-ICMP" /ip firewall filter add chain=input action=accept protocol=tcp dst-port=22,80,443,8080,8291 comment="Accept-Management" /ip firewall filter add chain=input action=drop comment="Drop-All-Other-Input" # Forward rules /ip firewall filter add chain=forward action=fasttrack-connection connection-state=established,related comment="FastTrack" /ip firewall filter add chain=forward action=accept connection-state=established,related comment="Accept-Established-Forward" /ip firewall filter add chain=forward action=drop connection-state=invalid comment="Drop-Invalid-Forward" /ip firewall filter add chain=forward action=accept comment="Accept-All-Forward" # NAT para redirecionamento hotspot /ip firewall nat add chain=dstnat dst-port=80 protocol=tcp hotspot=from-client \ action=redirect to-ports=64872 comment="Hotspot-HTTP-Redirect" # ============================ # WALLED GARDEN # ============================ :log info "Configurando walled garden..." /ip hotspot walled-garden add dst-host=login.wifi comment="Login-Page" /ip hotspot walled-garden add dst-host=192.168.100.1 comment="Router-Access" # ============================ # PÁGINA DE LOGIN CUSTOMIZADA # ============================ :log info "Criando página de login..." # Aguardar sistema de arquivos :delay 2s # Criar diretório hotspot se não existir :execute { :local content " WiFi Gratuito - Acesso Liberado
📶

WiFi Gratuito

Conecte-se gratuitamente à internet

\$(if error)
❌ Erro: \$(error)
\$(endif)
4 horas
de conexão
🔒
Seguro
e gratuito
\$(if popup == 'true') \$(endif) "; /file add name="hotspot/login.html" contents=$content; } # ============================ # CONFIGURAÇÃO DE EMAIL # ============================ :log info "Configurando servidor de email..." # Configurar email settings (usando Gmail SMTP) /tool e-mail set server=smtp.gmail.com port=587 \ start-tls=yes \ user=maulertech@gmail.com \ password=ynbm skmv wvkp eurt \ from=maulertech@gmail.com # IMPORTANTE: Para Gmail, você precisa: # 1. Ativar autenticação de 2 fatores # 2. Gerar uma "Senha de App" específica # 3. Substituir "sua_senha_app_aqui" pela senha de app gerada # ============================ # MONITORAMENTO COM NOTIFICAÇÃO # ============================ :log info "Configurando monitoramento com alertas..." # Scripts para notificação por email # Script quando WAN volta (UP) :global scriptWanUp { :local wanName $1 :local wanGateway $2 :local currentTime [/system clock get time] :local currentDate [/system clock get date] :local emailSubject "✅ WAN $wanName RESTAURADA - MikroTik LoadBalance" :local emailBody "ALERTA DE CONECTIVIDADE - WAN RESTAURADA 🌐 INFORMAÇÕES DO LINK: • WAN: $wanName • Gateway: $wanGateway • Status: ONLINE ✅ • Data/Hora: $currentDate $currentTime 📊 STATUS ATUAL DO SISTEMA: • Roteador: [/system identity get name] • Uptime: [/system resource get uptime] 🔄 AÇÃO EXECUTADA: • Rota automática restaurada • Load balance reativado • Tráfego sendo distribuído novamente Este é um alerta automático do sistema MikroTik. Link WAN $wanName foi restaurado e está funcionando normalmente. --- MikroTik LoadBalance System Monitoramento Automático" :log info "WAN $wanName restaurada - enviando email..." /tool e-mail send to="maulertech@gmail.com" subject=$emailSubject body=$emailBody } # Script quando WAN cai (DOWN) :global scriptWanDown { :local wanName $1 :local wanGateway $2 :local currentTime [/system clock get time] :local currentDate [/system clock get date] :local emailSubject "🚨 ALERTA: WAN $wanName INATIVA - MikroTik LoadBalance" :local emailBody "ALERTA CRÍTICO DE CONECTIVIDADE - WAN INATIVA ❌ INFORMAÇÕES DO LINK COM PROBLEMA: • WAN: $wanName • Gateway: $wanGateway • Status: OFFLINE ❌ • Data/Hora: $currentDate $currentTime 📊 STATUS ATUAL DO SISTEMA: • Roteador: [/system identity get name] • Uptime: [/system resource get uptime] • CPU: [/system resource get cpu-load]% • Memória: [/system resource get free-memory]/[/system resource get total-memory] 🔄 AÇÕES AUTOMÁTICAS EXECUTADAS: • Failover ativado automaticamente • Tráfego redirecionado para WANs ativas • Monitoramento contínuo ativo ⚠️ RECOMENDAÇÕES: • Verificar cabo de rede da $wanName • Verificar status do modem/roteador upstream • Contatar provedor se problema persistir Este é um alerta automático do sistema MikroTik. O sistema continuará monitorando e enviará nova notificação quando o link for restaurado. --- MikroTik LoadBalance System Monitoramento Automático" :log error "WAN $wanName inativa - enviando alerta..." /tool e-mail send to="maulertech@gmail.com" subject=$emailSubject body=$emailBody } # Netwatch para WAN1 /tool netwatch add host=192.168.0.1 interval=30s timeout=10s \ up-script=":global scriptWanUp; \$scriptWanUp \"WAN1\" \"192.168.0.1\"" \ down-script=":global scriptWanDown; \$scriptWanDown \"WAN1\" \"192.168.0.1\"" \ comment="Monitor-WAN1-Gateway" # Netwatch para WAN2 /tool netwatch add host=192.168.1.1 interval=30s timeout=10s \ up-script=":global scriptWanUp; \$scriptWanUp \"WAN2\" \"192.168.1.1\"" \ down-script=":global scriptWanDown; \$scriptWanDown \"WAN2\" \"192.168.1.1\"" \ comment="Monitor-WAN2-Gateway" # Netwatch para WAN3 /tool netwatch add host=192.168.2.1 interval=30s timeout=10s \ up-script=":global scriptWanUp; \$scriptWanUp \"WAN3\" \"192.168.2.1\"" \ down-script=":global scriptWanDown; \$scriptWanDown \"WAN3\" \"192.168.2.1\"" \ comment="Monitor-WAN3-Gateway" # Monitor adicional para internet geral /tool netwatch add host=8.8.8.8 interval=60s timeout=5s \ up-script=":log info \"Conectividade Internet OK\"" \ down-script=":log error \"ALERTA: Sem conectividade com a Internet\"; /tool e-mail send to=\"maulertech@gmail.com\" subject=\"🚨 SEM INTERNET - MikroTik\" body=\"Todas as WANs podem estar inativas. Verificação urgente necessária.\"" \ comment="Monitor-Internet-Geral" /tool netwatch add host=1.1.1.1 interval=30s timeout=5s \ up-script=":log info \"Internet OK - Cloudflare respondendo\"" \ down-script=":log error \"Internet DOWN - Cloudflare não responde\"" \ comment="Monitor-Internet-Cloudflare" # Logs do sistema /system logging add topics=info,error,warning action=memory # ============================ # CONFIGURAÇÕES FINAIS # ============================ :log info "Aplicando configurações finais..." # Aguardar sistema processar configurações :delay 3s # Verificar status do hotspot :if ([/ip hotspot print count-only] > 0) do={ :log info "✅ Hotspot configurado com sucesso" } else={ :log error "❌ Erro na configuração do hotspot" } # Verificar rotas :if ([/ip route print count-only where dst-address="0.0.0.0/0"] > 0) do={ :log info "✅ Rotas configuradas com sucesso" } else={ :log error "❌ Erro na configuração das rotas" } # ============================ # BACKUP E INFORMAÇÕES FINAIS # ============================ :log info "Criando backup da configuração..." /system backup save name=("config-completo-" . [/system clock get date]) # Salvar configuração /export file=("export-completo-" . [/system clock get date]) :delay 2s # ============================ # RELATÓRIO FINAL # ============================ :log info "========================================" :log info "🎉 CONFIGURAÇÃO CONCLUÍDA COM SUCESSO!" :log info "========================================" :log info "📧 EMAIL E MONITORAMENTO:" :log info "• Email de alertas: maulertech@gmail.com" :log info "• Monitoramento: A cada 30 segundos" :log info "• Alertas automáticos: WAN UP/DOWN" :log info "• ⚠️ CONFIGURE A SENHA DE APP DO GMAIL!" :log info "" :log info "📡 INFORMAÇÕES DA REDE:" :log info "• LAN Principal: 10.0.0.1/24 (ether4)" :log info "• Hotspot Social: 192.168.100.1/24 (ether5)" :log info "• WAN1: 192.168.0.100/24 → Gateway: 192.168.0.1 (ether1)" :log info "• WAN2: 192.168.1.100/24 → Gateway: 192.168.1.1 (ether2)" :log info "• WAN3: 192.168.2.100/24 → Gateway: 192.168.2.1 (ether3)" :log info "" :log info "🔗 LOAD BALANCE:" :log info "• Distribuição: 33% cada WAN" :log info "• Failover: WAN1 → WAN2 → WAN3" :log info "• Monitoramento: Ativo (ping test)" :log info "" :log info "📶 HOTSPOT SOCIAL:" :log info "• URL de Login: http://192.168.100.1" :log info "• Alternativo: http://login.wifi" :log info "• Método: Login por email" :log info "• Tempo de sessão: 4 horas" :log info "• Usuário admin: admin / 123456" :log info "" :log info "🛠️ COMANDOS ÚTEIS:" :log info "• Status hotspot: /ip hotspot active print" :log info "• Monitorar WANs: /tool netwatch print" :log info "• Ver rotas ativas: /ip route print where active=yes" :log info "• Logs do sistema: /log print" :log info "• Tráfego interfaces: /interface monitor-traffic wan1,wan2,wan3" :log info "" :log info "✅ Sistema pronto para uso!" :log info "========================================" # ============================ # TESTE AUTOMÁTICO (OPCIONAL) # ============================ :log info "Executando testes básicos..." # Teste de email (opcional) :log info "Enviando email de teste..." :do { /tool e-mail send to="maulertech@gmail.com" \ subject="✅ MikroTik Configurado - Teste de Email" \ body="Sistema MikroTik configurado com sucesso! 🎉 CONFIGURAÇÃO CONCLUÍDA: • Load Balance: 3 WANs ativas • Hotspot Social: Funcionando • Monitoramento: Ativo • Alertas por email: Configurados O sistema está monitorando as WANs e enviará alertas automáticos em caso de falha. Este é um email de teste do sistema de monitoramento. --- MikroTik LoadBalance System" :log info "✅ Email de teste enviado" } on-error={ :log warning "⚠️ Erro ao enviar email de teste - Verificar configuração SMTP" } :local testPing [/ping 8.8.8.8 count=3] :if ($testPing > 0) do={ :log info "✅ Teste de ping: OK ($testPing pacotes recebidos)" } else={ :log warning "⚠️ Teste de ping: Falhou - Verificar conectividade WAN" } # Testar resolução DNS :do { :resolve "google.com" :log info "✅ Teste DNS: OK" } on-error={ :log warning "⚠️ Teste DNS: Falhou - Verificar configuração DNS" } :log info "🏁 Configuração e testes concluídos!" :log info "Para acessar o hotspot, conecte um dispositivo na ether5"