Skip to content

Instantly share code, notes, and snippets.

@matheuseduardo
Created August 29, 2025 20:27
Show Gist options
  • Save matheuseduardo/f74d3cde0ac06e72819de9e73c825f3c to your computer and use it in GitHub Desktop.
Save matheuseduardo/f74d3cde0ac06e72819de9e73c825f3c to your computer and use it in GitHub Desktop.
scripts para diagnósticos de rede

🔎 Network Diagnose Scripts

Scripts para diagnóstico de problemas de conexão de rede, disponíveis em duas versões:

  • net-diagnose.sh → Shell Script (Linux/macOS)
  • net-diagnose.ps1 → PowerShell Script (Windows)

📋 Funcionalidades

Os scripts realizam uma série de testes automáticos para identificar possíveis falhas na rede:

  • Verificação de interface de rede (IPv4 / IPv6).
  • Checagem de gateway e conectividade com o roteador.
  • Teste de resolução DNS (inclui fallback em DNS público).
  • Teste de conectividade com a Internet (ICMP + HTTP/HTTPS).
  • Medição de latência e perda de pacotes.
  • Execução de traceroute até o Google (8.8.8.8).
  • Teste de velocidade de download (via speedtest se disponível ou arquivo de teste).
  • Checagem de erros RX/TX na interface de rede.
  • Geração de log automático com todos os resultados.

🐧 Uso no Linux/macOS (Bash)

Pré-requisitos

  • bash, ip, ping, nslookup, curl
  • Opcional: traceroute ou tracepath, speedtest-cli

Execução

chmod +x net-diagnose.sh
./net-diagnose.sh <interface>

Exemplo:

./net-diagnose.sh eth0

Se nenhuma interface for informada, o script exibirá as interfaces disponíveis e pedirá para escolher uma.

Saída esperada

📡 Interface: eth0
✅ IPv4: 192.168.1.10
✅ Gateway acessível (192.168.1.1)
✅ DNS OK (google.com → 142.250.219.14)
✅ Conexão à internet (IPv4 ICMP) OK
📊 Latência média: 12 ms | Perda: 0 %
🔍 Traceroute até 8.8.8.8...
   1  192.168.1.1
   2  10.0.0.1
   3  8.8.8.8
...
✅ Diagnóstico concluído. Log salvo em: /tmp/netdiag-YYYYMMDD-HHMM.log

🪟 Uso no Windows (PowerShell)

Pré-requisitos

  • Windows 10+ com PowerShell 5.1 ou superior
  • Cmdlets: Get-NetAdapter, Test-Connection, Resolve-DnsName
  • Opcional: tracert, Speedtest CLI

Execução

Abra o PowerShell como Administrador e rode:

.\net-diagnose.ps1 -InterfaceAlias "Ethernet"

Ou simplesmente:

.\net-diagnose.ps1

(nesse caso ele listará as interfaces disponíveis e pedirá para escolher uma).

Saída esperada

📡 Interface: Ethernet
✅ IPv4: 192.168.1.20
⚠️ Nenhum IPv6 encontrado
✅ Gateway acessível (192.168.1.1)
✅ DNS OK (google.com → 142.250.219.14)
✅ Conexão IPv4 ICMP OK
✅ Conexão HTTP/HTTPS OK
📊 Latência média: 15.2 ms | Perda: 0 %
🔍 Traceroute até 8.8.8.8 (máx 5 saltos):
   1   192.168.1.1
   2   10.0.0.1
   3   8.8.8.8
🔍 Testando velocidade (Speedtest CLI)...
Download: 95 Mbps | Upload: 92 Mbps
✅ Sem erros RX em Ethernet
✅ Diagnóstico concluído. Log salvo em: C:\Temp\netdiag-YYYYMMDD-HHMMSS.log

📂 Estrutura recomendada

network-diagnose/
├── net-diagnose.sh     # versão Bash/Linux
├── net-diagnose.ps1    # versão PowerShell/Windows
└── README.md           # documentação

📝 Observações

  • Ambos os scripts geram logs automáticos (Linux → /tmp/..., Windows → C:\Temp\...).
  • Resultados podem variar dependendo da rede e permissões do usuário.
  • Execução em modo administrador/root pode ser necessária para algumas funções.
<#
=============================================================
Script de Diagnóstico de Rede - PowerShell (Versão 1.0)
Autor: Matheus Eduardo (criado com auxílio de IA's - chatgpt, grok e gemini)
=============================================================
#>
param(
[string]$InterfaceAlias = ""
)
# --- Configurações ---
$LogFile = "C:\Temp\netdiag-$((Get-Date).ToString('yyyyMMdd-HHmmss')).log"
New-Item -ItemType Directory -Force -Path (Split-Path $LogFile) | Out-Null
function Log {
param([string]$Message)
$Message | Tee-Object -FilePath $LogFile -Append
}
# --- Funções de Diagnóstico ---
function Get-NetworkInterfaces {
Get-NetAdapter | Where-Object { $_.Status -eq "Up" } | Select-Object -ExpandProperty Name
}
function Check-IP {
param($Iface)
$IPv4 = (Get-NetIPAddress -InterfaceAlias $Iface -AddressFamily IPv4 -ErrorAction SilentlyContinue).IPAddress
$IPv6 = (Get-NetIPAddress -InterfaceAlias $Iface -AddressFamily IPv6 -ErrorAction SilentlyContinue).IPAddress
if ($IPv4) { Log "✅ IPv4: $IPv4" } else { Log "❌ Nenhum IPv4 em $Iface" }
if ($IPv6) { Log "✅ IPv6: $IPv6" } else { Log "⚠️ Nenhum IPv6 em $Iface" }
}
function Get-Gateway {
(Get-NetRoute -DestinationPrefix "0.0.0.0/0" -ErrorAction SilentlyContinue | Select-Object -First 1).NextHop
}
function Check-Router {
param($GW)
if (Test-Connection -ComputerName $GW -Count 3 -Quiet) {
Log "✅ Gateway acessível ($GW)"
} else {
Log "❌ Falha ao alcançar gateway ($GW)"
}
}
function Check-DNS {
try {
$Result = Resolve-DnsName "google.com" -ErrorAction Stop | Where-Object { $_.IPAddress } | Select-Object -First 1
if ($Result) {
Log "✅ DNS OK (google.com → $($Result.IPAddress))"
}
} catch {
Log "❌ Falha na resolução DNS"
# Testa com DNS do Google
try {
$AltResult = Resolve-DnsName "google.com" -Server 8.8.8.8 -ErrorAction Stop | Select-Object -First 1
if ($AltResult) {
Log "⚠️ Resolução funciona com DNS externo (8.8.8.8)"
}
} catch { }
}
}
function Check-Internet {
if (Test-Connection -ComputerName 8.8.8.8 -Count 3 -Quiet) {
Log "✅ Conexão IPv4 ICMP OK"
} else {
Log "❌ Sem conexão IPv4 ICMP (8.8.8.8)"
}
try {
$Resp = Invoke-WebRequest -Uri "https://www.google.com" -UseBasicParsing -TimeoutSec 5
if ($Resp.StatusCode -eq 200) {
Log "✅ Conexão HTTP/HTTPS OK"
}
} catch {
Log "❌ HTTP/HTTPS inacessível"
}
}
function Check-Latency {
$Ping = Test-Connection -ComputerName 8.8.8.8 -Count 10
if ($Ping) {
$Avg = ($Ping | Measure-Object ResponseTime -Average).Average
$Loss = 100 - (($Ping | Measure-Object).Count * 100 / 10)
Log "📊 Latência média: $([math]::Round($Avg,2)) ms | Perda: $Loss %"
}
}
function Check-Traceroute {
Log "🔍 Traceroute até 8.8.8.8 (máx 5 saltos):"
try {
tracert -h 5 8.8.8.8 | ForEach-Object { Log " $_" }
} catch {
Log "⚠️ Traceroute não disponível"
}
}
function Check-Speed {
# Se o módulo Speedtest estiver instalado (Speedtest.net CLI da Ookla)
if (Get-Command speedtest -ErrorAction SilentlyContinue) {
Log "🔍 Testando velocidade (Speedtest CLI)..."
speedtest --accept-license --accept-gdpr | Tee-Object -FilePath $LogFile -Append
} else {
Log "🔍 Testando velocidade (download 10MB de Hetzner)..."
$Url = "http://speedtest.wdc01.softlayer.com/downloads/test100.zip"
$Temp = "$env:TEMP\speedtest.bin"
$sw = [System.Diagnostics.Stopwatch]::StartNew()
try {
Invoke-WebRequest -Uri $Url -OutFile $Temp -UseBasicParsing -TimeoutSec 60
$sw.Stop()
$Elapsed = $sw.Elapsed.TotalSeconds
if ($Elapsed -gt 0) {
$Rate = [math]::Round((10 / $Elapsed),2)
Log " ➝ Velocidade aproximada: $Rate MB/s"
}
} catch {
Log "❌ Falha ao medir velocidade"
}
Remove-Item $Temp -ErrorAction SilentlyContinue
}
}
function Check-Errors {
param($Iface)
$Stats = Get-NetAdapterStatistics -Name $Iface
if ($Stats.ReceivedErrors -gt 0) {
Log "⚠️ Erros RX detectados em ${Iface}: $($Stats.ReceivedErrors)"
} else {
Log "✅ Sem erros RX em ${Iface}"
}
}
# --- Execução ---
Log "=== Diagnóstico de Rede (PowerShell) ==="
Log "Log salvo em: $LogFile"
Log "----------------------------------------"
# Selecionar interface
if (-not $InterfaceAlias) {
$Ifaces = Get-NetworkInterfaces
Log "Interfaces disponíveis: $Ifaces"
$InterfaceAlias = Read-Host "Digite a interface para diagnosticar"
}
Log "📡 Interface: $InterfaceAlias"
Log "----------------------------------------"
Check-IP $InterfaceAlias
$GW = Get-Gateway
if ($GW) { Check-Router $GW } else { Log "❌ Nenhum gateway encontrado" }
Check-DNS
Check-Internet
Check-Latency
Check-Traceroute
Check-Speed
Check-Errors $InterfaceAlias
Log "----------------------------------------"
Log "✅ Diagnóstico concluído. Log salvo em: $LogFile"
#!/bin/bash
# ============================================================
# Script de Diagnóstico de Rede - Versão 3.0
# Autor: Matheus Eduardo (criado com auxílio de IA's - chatgpt, grok e gemini)
# ============================================================
# --- Configurações ---
LOGFILE="/tmp/netdiag-$(date +%Y%m%d-%H%M%S).log"
# Cores
GREEN="\e[32m"
RED="\e[31m"
YELLOW="\e[33m"
RESET="\e[0m"
# --- Funções Utilitárias ---
log() {
echo -e "$1" | tee -a "$LOGFILE"
}
command_exists() {
command -v "$1" >/dev/null 2>&1
}
# --- Funções de Diagnóstico ---
check_dependencies() {
local DEPENDENCIES=("ip" "ping" "nslookup" "curl" "grep" "awk")
for cmd in "${DEPENDENCIES[@]}"; do
if ! command_exists "$cmd"; then
log "${RED}❌ Erro: comando '$cmd' não encontrado.${RESET}"
exit 1
fi
done
}
list_interfaces() {
ip -o link show | awk -F': ' '{print $2}' | grep -v 'lo'
}
check_ip() {
local IFACE="$1"
local IPV4=$(ip -4 addr show "$IFACE" | grep -oP '(?<=inet\s)\d+(\.\d+){3}')
local IPV6=$(ip -6 addr show "$IFACE" | grep -oP '(?<=inet6\s)[0-9a-f:]+')
if [ -z "$IPV4" ]; then
log "${RED}❌ Nenhum IPv4 válido encontrado em $IFACE.${RESET}"
else
log "${GREEN}✅ IPv4: $IPV4${RESET}"
fi
if [ -n "$IPV6" ]; then
log "${GREEN}✅ IPv6: $IPV6${RESET}"
else
log "${YELLOW}⚠️ Nenhum IPv6 encontrado em $IFACE.${RESET}"
fi
}
get_gateway() {
ip route | grep default | awk '{print $3}' | head -n1
}
check_router_connection() {
local GW="$1"
if ping -c 3 -W 1 "$GW" >/dev/null 2>&1; then
log "${GREEN}✅ Gateway acessível ($GW)${RESET}"
else
log "${RED}❌ Falha ao alcançar gateway ($GW)${RESET}"
fi
}
check_dns() {
local TEST_DOMAIN="google.com"
local DNS=$(nslookup $TEST_DOMAIN 2>/dev/null | grep "Address:" | tail -n1 | awk '{print $2}')
if [ -n "$DNS" ]; then
log "${GREEN}✅ DNS OK ($TEST_DOMAIN → $DNS)${RESET}"
else
log "${RED}❌ Falha de resolução DNS.${RESET}"
# Testar com DNS do Google
if nslookup $TEST_DOMAIN 8.8.8.8 >/dev/null 2>&1; then
log "${YELLOW}⚠️ Resolução funciona com DNS externo (8.8.8.8).${RESET}"
fi
fi
}
check_internet() {
if ping -c 3 -W 1 8.8.8.8 >/dev/null 2>&1; then
log "${GREEN}✅ Conexão à internet (IPv4 ICMP) OK${RESET}"
else
log "${RED}❌ Sem conexão IPv4 ICMP (8.8.8.8)${RESET}"
fi
if command_exists ping6; then
if ping6 -c 3 -W 1 2001:4860:4860::8888 >/dev/null 2>&1; then
log "${GREEN}✅ Conexão à internet (IPv6 ICMP) OK${RESET}"
else
log "${YELLOW}⚠️ IPv6 não acessível (2001:4860:4860::8888)${RESET}"
fi
fi
if curl -s --head https://www.google.com --max-time 5 >/dev/null; then
log "${GREEN}✅ Conexão HTTP/HTTPS OK${RESET}"
else
log "${RED}❌ HTTP/HTTPS inacessível${RESET}"
fi
}
check_latency() {
log "${YELLOW}🔍 Medindo latência e perda de pacotes...${RESET}"
PING_OUT=$(ping -c 10 -q 8.8.8.8)
LOSS=$(echo "$PING_OUT" | grep -oP '\d+(?=% packet loss)')
AVG=$(echo "$PING_OUT" | grep -oP '(?<=avg = )[\d\.]+')
log " ➝ Perda: ${LOSS}% | Latência média: ${AVG} ms"
}
check_traceroute() {
if command_exists traceroute; then
log "${YELLOW}🔍 Executando traceroute até 8.8.8.8...${RESET}"
traceroute -m 5 8.8.8.8 | tee -a "$LOGFILE"
elif command_exists tracepath; then
log "${YELLOW}🔍 Executando tracepath até 8.8.8.8...${RESET}"
tracepath 8.8.8.8 | head -n 5 | tee -a "$LOGFILE"
else
log "${YELLOW}⚠️ traceroute/tracepath não instalado.${RESET}"
fi
}
check_speed() {
if command_exists speedtest; then
log "${YELLOW}🔍 Testando velocidade (speedtest-cli)...${RESET}"
speedtest --simple --bytes | tee -a "$LOGFILE"
else
log "${YELLOW}🔍 Testando velocidade (download de 10MB)...${RESET}"
START=$(date +%s)
curl -s -o /dev/null https://speed.hetzner.de/10MB.bin
END=$(date +%s)
ELAPSED=$((END - START))
if [ $ELAPSED -gt 0 ]; then
RATE=$((10 / ELAPSED))
log " ➝ Velocidade aproximada: ~${RATE} MB/s"
else
log "${RED}❌ Falha ao medir velocidade.${RESET}"
fi
fi
}
check_errors() {
local IFACE="$1"
ERRORS=$(ip -s link show "$IFACE" | grep "RX:" -A1 | tail -n1 | awk '{print $3}')
if [ -n "$ERRORS" ] && [ "$ERRORS" -gt 0 ] 2>/dev/null; then
log "${YELLOW}⚠️ Erros RX detectados em $IFACE: $ERRORS${RESET}"
else
log "${GREEN}✅ Sem erros RX em $IFACE${RESET}"
fi
}
# --- Fluxo Principal ---
echo "=== Diagnóstico de Rede (v3.0) ==="
echo "Log: $LOGFILE"
echo "----------------------------------" | tee -a "$LOGFILE"
check_dependencies
# Escolher interface
if [ -z "$1" ]; then
IFACES=$(list_interfaces)
log "${YELLOW}Interfaces disponíveis:${RESET}"
echo "$IFACES"
read -rp "Digite a interface para diagnosticar: " IFACE
else
IFACE="$1"
fi
log "📡 Interface: $IFACE"
echo "----------------------------------" | tee -a "$LOGFILE"
check_ip "$IFACE"
GATEWAY=$(get_gateway)
[ -n "$GATEWAY" ] && check_router_connection "$GATEWAY" || log "${RED}❌ Nenhum gateway padrão encontrado${RESET}"
check_dns
check_internet
check_latency
check_traceroute
check_speed
check_errors "$IFACE"
echo "----------------------------------" | tee -a "$LOGFILE"
log "✅ Diagnóstico concluído. Log salvo em: $LOGFILE"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment