Saltar a contenido

Traceroute Cheatsheet

■/div titulada

Sinopsis

Traceroute es una herramienta de diagnóstico de red fundamental que rastrea los paquetes de ruta tomar de su computadora a un host de destino a través de Internet o red local. Revela cada router intermedio (hop) a lo largo del camino, mostrando mediciones de latencia y ayudando a identificar cuellos de botella de red, problemas de enrutamiento y problemas de conectividad.

Características clave

  • Path Discovery: Revela la ruta completa a un destino
  • Hop-by-Hop Analysis: muestra cada router a lo largo del camino
  • ** Medición de latencia**: Tiempo de ida y vuelta para cada salto
  • Route Troubleshooting Identifica dónde se retrasan o bajan los paquetes
  • Mapa de Topología de Redes: Comprender la infraestructura de red
  • Tracing geográfico: Identificar las ubicaciones geográficas de los tubos
  • ** Apoyo al Protocolo**: opciones de localización ICMP, UDP y TCP
  • IPv4 y IPv6 Soporte: Análisis de red de doble plataforma

Instalación y disponibilidad

Linux Systems

# Most Linux distributions include traceroute by default
which traceroute

# Install if missing (Ubuntu/Debian)
sudo apt update
sudo apt install traceroute

# Install on CentOS/RHEL/Fedora
sudo yum install traceroute
# or
sudo dnf install traceroute

# Install on Arch Linux
sudo pacman -S traceroute

# Verify installation
traceroute --version

Sistemas Windows

# Windows includes tracert by default
where tracert

# Enhanced traceroute tools for Windows
# Download WinMTR (GUI traceroute)
# https://sourceforge.net/projects/winmtr/

# Install via Chocolatey
choco install winmtr

# Install via Scoop
scoop install winmtr

# PowerShell Test-NetConnection (modern alternative)
Test-NetConnection -ComputerName google.com -TraceRoute

macOS Systems

# macOS includes traceroute by default
which traceroute

# Install enhanced version via Homebrew
brew install traceroute

# Install mtr (enhanced traceroute)
brew install mtr

# Verify installation
traceroute -V

Uso básico

Comandos Traceroute estándar

# Basic traceroute to a hostname
traceroute google.com

# Traceroute to an IP address
traceroute 8.8.8.8

# Windows equivalent
tracert google.com

# Specify maximum number of hops
traceroute -m 20 google.com

# Use specific interface
traceroute -i eth0 google.com

# Set packet size
traceroute -s 192.168.1.100 google.com

# Verbose output
traceroute -v google.com

Opciones de protocolo

# Use ICMP instead of UDP (requires root)
sudo traceroute -I google.com

# Use TCP SYN packets
sudo traceroute -T google.com

# Specify destination port
traceroute -p 80 google.com

# Use IPv6
traceroute6 google.com
# or
traceroute -6 google.com

# Disable hostname resolution
traceroute -n google.com

# Set timeout for each probe
traceroute -w 5 google.com

Opciones avanzadas

# Send multiple probes per hop
traceroute -q 5 google.com

# Set initial TTL value
traceroute -f 5 google.com

# Use specific source address
traceroute -s 192.168.1.100 google.com

# Set Type of Service (ToS)
traceroute -t 0x10 google.com

# Enable socket level debugging
traceroute -d google.com

# Don't fragment packets
traceroute -F google.com

# Use loose source routing
traceroute -g 192.168.1.1 google.com

Comandos de plataforma-específicos

Linux Traceroute

# Standard Linux traceroute
traceroute [options] destination

# Common options
traceroute -n google.com              # No DNS resolution
traceroute -I google.com              # Use ICMP
traceroute -T google.com              # Use TCP
traceroute -U google.com              # Use UDP (default)
traceroute -p 443 google.com          # Specific port
traceroute -m 15 google.com           # Max 15 hops
traceroute -w 3 google.com            # 3 second timeout
traceroute -q 1 google.com            # 1 probe per hop
traceroute -f 3 google.com            # Start at hop 3

# Advanced Linux options
traceroute --mtu google.com           # Discover path MTU
traceroute --back google.com          # Print hop addresses numerically and symbolically
traceroute -A google.com              # Lookup AS numbers
traceroute -V google.com              # Version information

Tracert de Windows

# Standard Windows tracert
tracert [options] destination

# Common options
tracert -d google.com                 # Don't resolve hostnames
tracert -h 15 google.com              # Maximum 15 hops
tracert -w 3000 google.com            # 3 second timeout
tracert -4 google.com                 # Force IPv4
tracert -6 google.com                 # Force IPv6

# PowerShell alternatives
Test-NetConnection -ComputerName google.com -TraceRoute
Test-NetConnection -ComputerName google.com -TraceRoute -Hops 15

# Enhanced PowerShell traceroute function
function Trace-Route {
    param(
        [string]$Destination,
        [int]$MaxHops = 30,
        [int]$Timeout = 3000
    )

    $result = Test-NetConnection -ComputerName $Destination -TraceRoute -Hops $MaxHops

    Write-Host "Tracing route to $Destination"
    Write-Host "Maximum hops: $MaxHops"
    Write-Host ""

    for ($i = 0; $i -lt $result.TraceRoute.Count; $i++) {
        $hop = $i + 1
        $address = $result.TraceRoute[$i]

        # Measure latency
        $ping = Test-Connection -ComputerName $address -Count 1 -Quiet
        if ($ping) {
            $latency = (Test-Connection -ComputerName $address -Count 1).ResponseTime
            Write-Host "$hop    $latency ms    $address"
        } else {
            Write-Host "$hop    *    $address"
        }
    }
}

# Usage
Trace-Route -Destination google.com -MaxHops 20

macOS Traceroute

# macOS traceroute (similar to Linux)
traceroute [options] destination

# macOS specific options
traceroute -A google.com              # AS number lookup
traceroute -e google.com              # Show ICMP extensions
traceroute -P google.com              # Use UDP datagrams
traceroute -S google.com              # Print summary statistics

# Network utility GUI
# Applications → Utilities → Network Utility → Traceroute

Técnicas de análisis avanzado

Interpretación de Traceroute Producto

# Example traceroute output analysis
traceroute google.com

# Sample output:
# traceroute to google.com (172.217.12.142), 30 hops max, 60 byte packets
#  1  192.168.1.1 (192.168.1.1)  1.234 ms  1.123 ms  1.456 ms
#  2  10.0.0.1 (10.0.0.1)  15.234 ms  14.567 ms  16.123 ms
#  3  * * *
#  4  203.0.113.1 (203.0.113.1)  25.123 ms  24.567 ms  26.234 ms

# Analysis interpretation:
echo "Hop 1: Local gateway (1-2ms) - Normal"
echo "Hop 2: ISP router (14-16ms) - Normal"
echo "Hop 3: Timeouts (*) - Possible firewall or rate limiting"
echo "Hop 4: ISP backbone (24-26ms) - Normal"

# Common patterns and meanings:
echo "Patterns to look for:"
echo "- Sudden latency increase: Bottleneck or geographic distance"
echo "- Timeouts (*): Firewall, rate limiting, or router configuration"
echo "- Asymmetric routing: Different paths for forward/return traffic"
echo "- High jitter: Network congestion or unstable links"

Análisis de la ruta automatizada

#!/bin/bash
# advanced_traceroute_analysis.sh

TARGET="$1"
if [ -z "$TARGET" ]; then
    echo "Usage: $0 <target>"
    exit 1
fi

echo "Advanced Traceroute Analysis for $TARGET"
echo "========================================"

# Perform traceroute and save output
TRACE_OUTPUT=$(traceroute -n "$TARGET" 2>/dev/null)
echo "$TRACE_OUTPUT" > "/tmp/trace_${TARGET}.txt"

# Extract hop information
echo "Hop Analysis:"
echo "-------------"

echo "$TRACE_OUTPUT" | grep -E "^ *[0-9]+" | while read line; do
    HOP=$(echo "$line" | awk '{print $1}')
    IP=$(echo "$line" | awk '{print $2}')
    TIME1=$(echo "$line" | awk '{print $3}')
    TIME2=$(echo "$line" | awk '{print $5}')
    TIME3=$(echo "$line" | awk '{print $7}')

    # Skip if hop shows timeouts
    if [[ "$IP" == "*" ]]; then
        echo "Hop $HOP: Timeout - Possible firewall or rate limiting"
        continue
    fi

    # Calculate average latency
    if [[ "$TIME1" =~ ^[0-9]+\.?[0-9]*$ ]] && [[ "$TIME2" =~ ^[0-9]+\.?[0-9]*$ ]] && [[ "$TIME3" =~ ^[0-9]+\.?[0-9]*$ ]]; then
        AVG=$(echo "scale=3; ($TIME1 + $TIME2 + $TIME3) / 3" | bc)

        # Analyze latency
        if (( $(echo "$AVG < 10" | bc -l) )); then
            STATUS="Excellent"
        elif (( $(echo "$AVG < 50" | bc -l) )); then
            STATUS="Good"
        elif (( $(echo "$AVG < 150" | bc -l) )); then
            STATUS="Acceptable"
        else
            STATUS="Poor"
        fi

        echo "Hop $HOP: $IP - Avg: ${AVG}ms ($STATUS)"

        # Check for significant latency increases
        if [ "$HOP" -gt 1 ]; then
            PREV_AVG=$(echo "$TRACE_OUTPUT" | grep -E "^ *$(($HOP-1))" | awk '{print ($3+$5+$7)/3}')
            if [[ "$PREV_AVG" =~ ^[0-9]+\.?[0-9]*$ ]]; then
                INCREASE=$(echo "scale=3; $AVG - $PREV_AVG" | bc)
                if (( $(echo "$INCREASE > 50" | bc -l) )); then
                    echo "  WARNING: Significant latency increase (+${INCREASE}ms)"
                fi
            fi
        fi
    fi
done

# Geographic analysis (requires geoip tools)
echo ""
echo "Geographic Analysis:"
echo "-------------------"

if command -v geoiplookup >/dev/null 2>&1; then
    echo "$TRACE_OUTPUT" | grep -oE "([0-9]{1,3}\.){3}[0-9]{1,3}" | sort -u | while read ip; do
        if [[ ! "$ip" =~ ^(10\.|172\.(1[6-9]|2[0-9]|3[01])\.|192\.168\.) ]]; then
            LOCATION=$(geoiplookup "$ip" | cut -d: -f2 | sed 's/^ *//')
            echo "$ip: $LOCATION"
        fi
    done
else
    echo "Install geoip-bin for geographic analysis"
fi

# Network analysis
echo ""
echo "Network Analysis:"
echo "----------------"

TOTAL_HOPS=$(echo "$TRACE_OUTPUT" | grep -c "^ *[0-9]")
TIMEOUT_HOPS=$(echo "$TRACE_OUTPUT" | grep -c "\*")
SUCCESS_RATE=$(echo "scale=2; (($TOTAL_HOPS - $TIMEOUT_HOPS) * 100) / $TOTAL_HOPS" | bc)

echo "Total hops: $TOTAL_HOPS"
echo "Timeout hops: $TIMEOUT_HOPS"
echo "Success rate: ${SUCCESS_RATE}%"

# Final assessment
if (( $(echo "$SUCCESS_RATE > 90" | bc -l) )); then
    echo "Overall assessment: Good connectivity"
elif (( $(echo "$SUCCESS_RATE > 70" | bc -l) )); then
    echo "Overall assessment: Moderate connectivity issues"
else
    echo "Overall assessment: Significant connectivity problems"
fi

Vigilancia de la ruta continua

#!/usr/bin/env python3
# continuous_traceroute_monitor.py

import subprocess
import time
import json
import datetime
import re
import statistics
from collections import defaultdict

class TracerouteMonitor:
    def __init__(self, target, interval=300):
        self.target = target
        self.interval = interval
        self.history = []
        self.hop_stats = defaultdict(list)

    def run_traceroute(self):
        """Execute traceroute and parse results"""
        try:
            # Run traceroute command
            result = subprocess.run(
                ['traceroute', '-n', self.target],
                capture_output=True,
                text=True,
                timeout=60
            )

            if result.returncode == 0:
                return self.parse_traceroute_output(result.stdout)
            else:
                print(f"Traceroute failed: {result.stderr}")
                return None

        except subprocess.TimeoutExpired:
            print("Traceroute timed out")
            return None
        except Exception as e:
            print(f"Error running traceroute: {e}")
            return None

    def parse_traceroute_output(self, output):
        """Parse traceroute output into structured data"""
        hops = []
        lines = output.strip().split('\n')[1:]  # Skip header line

        for line in lines:
            # Match hop lines: " 1  192.168.1.1  1.234 ms  1.123 ms  1.456 ms"
            hop_match = re.match(r'^\s*(\d+)\s+(\S+)\s+(.*)', line)
            if hop_match:
                hop_num = int(hop_match.group(1))
                ip = hop_match.group(2)
                times_str = hop_match.group(3)

                # Extract timing information
                times = []
                time_matches = re.findall(r'(\d+\.?\d*)\s*ms', times_str)
                for time_match in time_matches:
                    times.append(float(time_match))

                # Handle timeouts
                timeout_count = times_str.count('*')

                hop_data = {
                    'hop': hop_num,
                    'ip': ip if ip != '*' else None,
                    'times': times,
                    'timeouts': timeout_count,
                    'avg_time': statistics.mean(times) if times else None,
                    'min_time': min(times) if times else None,
                    'max_time': max(times) if times else None
                }

                hops.append(hop_data)

        return {
            'timestamp': datetime.datetime.now().isoformat(),
            'target': self.target,
            'hops': hops,
            'total_hops': len(hops)
        }

    def analyze_route_changes(self, current_trace):
        """Detect route changes compared to previous traces"""
        if not self.history:
            return []

        changes = []
        last_trace = self.history[-1]

        # Compare hop IPs
        current_ips = [hop['ip'] for hop in current_trace['hops']]
        last_ips = [hop['ip'] for hop in last_trace['hops']]

        if current_ips != last_ips:
            changes.append({
                'type': 'route_change',
                'description': 'Route path has changed',
                'previous_path': last_ips,
                'current_path': current_ips
            })

        # Compare hop counts
        if current_trace['total_hops'] != last_trace['total_hops']:
            changes.append({
                'type': 'hop_count_change',
                'description': f"Hop count changed from {last_trace['total_hops']} to {current_trace['total_hops']}"
            })

        # Analyze latency changes
        for i, hop in enumerate(current_trace['hops']):
            if i < len(last_trace['hops']) and hop['avg_time'] and last_trace['hops'][i]['avg_time']:
                current_avg = hop['avg_time']
                last_avg = last_trace['hops'][i]['avg_time']

                # Significant latency increase (>50ms or >50% increase)
                if (current_avg - last_avg > 50) or (current_avg > last_avg * 1.5):
                    changes.append({
                        'type': 'latency_increase',
                        'hop': hop['hop'],
                        'ip': hop['ip'],
                        'description': f"Latency increased from {last_avg:.2f}ms to {current_avg:.2f}ms"
                    })

        return changes

    def update_statistics(self, trace):
        """Update hop statistics for trend analysis"""
        for hop in trace['hops']:
            if hop['avg_time']:
                hop_key = f"{hop['hop']}_{hop['ip']}"
                self.hop_stats[hop_key].append({
                    'timestamp': trace['timestamp'],
                    'latency': hop['avg_time'],
                    'timeouts': hop['timeouts']
                })

    def generate_report(self):
        """Generate monitoring report"""
        if not self.history:
            return "No data collected yet"

        report = f"Traceroute Monitoring Report for {self.target}\n"
        report += f"{'='*50}\n"
        report += f"Monitoring period: {self.history[0]['timestamp']} to {self.history[-1]['timestamp']}\n"
        report += f"Total traces: {len(self.history)}\n\n"

        # Route stability analysis
        unique_routes = set()
        for trace in self.history:
            route_signature = tuple(hop['ip'] for hop in trace['hops'])
            unique_routes.add(route_signature)

        report += f"Route Stability:\n"
        report += f"- Unique routes observed: {len(unique_routes)}\n"
        if len(unique_routes) == 1:
            report += "- Route is stable (no changes detected)\n"
        else:
            report += "- Route instability detected (multiple paths observed)\n"

        # Hop performance analysis
        report += f"\nHop Performance Analysis:\n"
        for hop_key, measurements in self.hop_stats.items():
            if len(measurements) >= 3:  # Minimum measurements for analysis
                latencies = [m['latency'] for m in measurements]
                avg_latency = statistics.mean(latencies)
                min_latency = min(latencies)
                max_latency = max(latencies)
                std_dev = statistics.stdev(latencies) if len(latencies) > 1 else 0

                hop_num, ip = hop_key.split('_', 1)
                report += f"- Hop {hop_num} ({ip}):\n"
                report += f"  Average: {avg_latency:.2f}ms, Min: {min_latency:.2f}ms, Max: {max_latency:.2f}ms\n"
                report += f"  Std Dev: {std_dev:.2f}ms, Measurements: {len(measurements)}\n"

        return report

    def monitor(self, duration_hours=24):
        """Run continuous monitoring"""
        end_time = time.time() + (duration_hours * 3600)

        print(f"Starting traceroute monitoring for {self.target}")
        print(f"Duration: {duration_hours} hours, Interval: {self.interval} seconds")

        while time.time() < end_time:
            print(f"\n{datetime.datetime.now()}: Running traceroute...")

            trace = self.run_traceroute()
            if trace:
                # Analyze for changes
                changes = self.analyze_route_changes(trace)
                if changes:
                    print("CHANGES DETECTED:")
                    for change in changes:
                        print(f"  - {change['description']}")

                # Update statistics
                self.update_statistics(trace)
                self.history.append(trace)

                # Print current status
                print(f"Trace completed: {trace['total_hops']} hops")
                if trace['hops']:
                    final_hop = trace['hops'][-1]
                    if final_hop['avg_time']:
                        print(f"End-to-end latency: {final_hop['avg_time']:.2f}ms")

            # Wait for next interval
            time.sleep(self.interval)

        # Generate final report
        print("\n" + "="*50)
        print("MONITORING COMPLETED")
        print("="*50)
        print(self.generate_report())

        # Save data to file
        output_file = f"traceroute_monitor_{self.target}_{datetime.datetime.now().strftime('%Y%m%d_%H%M%S')}.json"
        with open(output_file, 'w') as f:
            json.dump(self.history, f, indent=2)
        print(f"\nData saved to: {output_file}")

def main():
    import argparse

    parser = argparse.ArgumentParser(description='Continuous Traceroute Monitor')
    parser.add_argument('target', help='Target hostname or IP address')
    parser.add_argument('--interval', type=int, default=300, help='Monitoring interval in seconds (default: 300)')
    parser.add_argument('--duration', type=int, default=24, help='Monitoring duration in hours (default: 24)')

    args = parser.parse_args()

    monitor = TracerouteMonitor(args.target, args.interval)
    monitor.monitor(args.duration)

if __name__ == "__main__":
    main()

Problemas de la red

Problemas de red comunes

# Identify common network issues using traceroute

# 1. High latency at specific hop
traceroute google.com | awk '
/^ *[0-9]+/ {
    hop = $1
    if ($3 ~ /^[0-9]+\./) {
        latency = $3
        if (latency > 100) {
            print "HIGH LATENCY at hop " hop ": " latency "ms (" $2 ")"
        }
    }
}'

# 2. Packet loss detection
function detect_packet_loss() {
    local target=$1
    echo "Detecting packet loss to $target..."

    traceroute "$target" | grep '\*' | while read line; do
        hop=$(echo "$line" | awk '{print $1}')
        echo "Packet loss detected at hop $hop"
    done
}

# 3. Route asymmetry detection
function check_route_asymmetry() {
    local target=$1
    echo "Checking route asymmetry to $target..."

    # Forward path
    echo "Forward path:"
    traceroute -n "$target" | grep -E "^ *[0-9]+" | awk '{print $1 ": " $2}'

    echo ""
    echo "Note: Use tools like traceroute from the destination back to check return path"
}

# 4. MTU discovery issues
function check_mtu_issues() {
    local target=$1
    echo "Checking for MTU issues to $target..."

    # Test with different packet sizes
    for size in 1472 1500 9000; do
        echo "Testing with ${size} byte packets:"
        ping -c 3 -s $size "$target" 2>/dev/null || echo "  Failed with ${size} bytes"
    done
}

# 5. DNS resolution delays
function check_dns_delays() {
    local target=$1
    echo "Checking DNS resolution delays..."

    # Compare numeric vs hostname traceroute
    echo "With DNS resolution:"
    time traceroute "$target" >/dev/null 2>&1

    echo "Without DNS resolution:"
    time traceroute -n "$target" >/dev/null 2>&1
}

Network Performance Analysis

#!/bin/bash
# network_performance_analysis.sh

TARGET="$1"
if [ -z "$TARGET" ]; then
    echo "Usage: $0 <target>"
    exit 1
fi

echo "Network Performance Analysis for $TARGET"
echo "========================================"

# 1. Basic connectivity test
echo "1. Basic Connectivity Test:"
if ping -c 3 "$TARGET" >/dev/null 2>&1; then
    echo "   ✓ Target is reachable"
    RTT=$(ping -c 3 "$TARGET" | tail -1 | awk -F'/' '{print $5}')
    echo "   Average RTT: ${RTT}ms"
else
    echo "   ✗ Target is not reachable"
    exit 1
fi

# 2. Traceroute analysis
echo ""
echo "2. Route Analysis:"
TRACE_OUTPUT=$(traceroute -n "$TARGET" 2>/dev/null)
echo "$TRACE_OUTPUT"

# Extract performance metrics
TOTAL_HOPS=$(echo "$TRACE_OUTPUT" | grep -c "^ *[0-9]")
TIMEOUT_HOPS=$(echo "$TRACE_OUTPUT" | grep -c "\*")

echo ""
echo "Route Statistics:"
echo "   Total hops: $TOTAL_HOPS"
echo "   Timeout hops: $TIMEOUT_HOPS"

# 3. Latency analysis per hop
echo ""
echo "3. Hop Latency Analysis:"
echo "$TRACE_OUTPUT" | grep -E "^ *[0-9]+" | while read line; do
    HOP=$(echo "$line" | awk '{print $1}')
    IP=$(echo "$line" | awk '{print $2}')

    if [[ "$IP" != "*" ]]; then
        # Extract all timing values
        TIMES=$(echo "$line" | grep -oE "[0-9]+\.[0-9]+ ms" | grep -oE "[0-9]+\.[0-9]+")

        if [ -n "$TIMES" ]; then
            # Calculate average
            AVG=$(echo "$TIMES" | awk '{sum+=$1; count++} END {if(count>0) print sum/count; else print 0}')

            # Categorize performance
            if (( $(echo "$AVG < 10" | bc -l) )); then
                STATUS="Excellent"
            elif (( $(echo "$AVG < 50" | bc -l) )); then
                STATUS="Good"
            elif (( $(echo "$AVG < 150" | bc -l) )); then
                STATUS="Acceptable"
            else
                STATUS="Poor"
            fi

            echo "   Hop $HOP ($IP): ${AVG}ms - $STATUS"
        fi
    else
        echo "   Hop $HOP: Timeout"
    fi
done

# 4. Bottleneck detection
echo ""
echo "4. Bottleneck Detection:"
PREV_LATENCY=0
echo "$TRACE_OUTPUT" | grep -E "^ *[0-9]+" | while read line; do
    HOP=$(echo "$line" | awk '{print $1}')
    IP=$(echo "$line" | awk '{print $2}')

    if [[ "$IP" != "*" ]]; then
        TIMES=$(echo "$line" | grep -oE "[0-9]+\.[0-9]+ ms" | grep -oE "[0-9]+\.[0-9]+")

        if [ -n "$TIMES" ]; then
            AVG=$(echo "$TIMES" | awk '{sum+=$1; count++} END {if(count>0) print sum/count; else print 0}')

            if [ "$HOP" -gt 1 ] && (( $(echo "$AVG - $PREV_LATENCY > 50" | bc -l) )); then
                INCREASE=$(echo "$AVG - $PREV_LATENCY" | bc)
                echo "   ⚠ Bottleneck detected at hop $HOP ($IP): +${INCREASE}ms"
            fi

            PREV_LATENCY=$AVG
        fi
    fi
done

# 5. Geographic analysis (if geoip available)
echo ""
echo "5. Geographic Analysis:"
if command -v geoiplookup >/dev/null 2>&1; then
    echo "$TRACE_OUTPUT" | grep -oE "([0-9]{1,3}\.){3}[0-9]{1,3}" | sort -u | while read ip; do
        # Skip private IP ranges
        if [[ ! "$ip" =~ ^(10\.|172\.(1[6-9]|2[0-9]|3[01])\.|192\.168\.) ]]; then
            LOCATION=$(geoiplookup "$ip" 2>/dev/null | cut -d: -f2 | sed 's/^ *//')
            if [ -n "$LOCATION" ]; then
                echo "   $ip: $LOCATION"
            fi
        fi
    done
else
    echo "   Install geoip-bin for geographic analysis"
fi

# 6. Recommendations
echo ""
echo "6. Recommendations:"

# Check for high latency
HIGH_LATENCY=$(echo "$TRACE_OUTPUT" | grep -oE "[0-9]+\.[0-9]+ ms" | grep -oE "[0-9]+\.[0-9]+" | awk '$1 > 200 {print $1}' | head -1)
if [ -n "$HIGH_LATENCY" ]; then
    echo "   ⚠ High latency detected (${HIGH_LATENCY}ms)"
    echo "     - Check for network congestion"
    echo "     - Consider alternative routes or providers"
fi

# Check for timeouts
if [ "$TIMEOUT_HOPS" -gt 0 ]; then
    echo "   ⚠ Timeouts detected ($TIMEOUT_HOPS hops)"
    echo "     - May indicate firewall filtering"
    echo "     - Could be rate limiting or router configuration"
fi

# Check hop count
if [ "$TOTAL_HOPS" -gt 20 ]; then
    echo "   ⚠ High hop count ($TOTAL_HOPS hops)"
    echo "     - Route may not be optimal"
    echo "     - Consider using CDN or closer servers"
fi

echo ""
echo "Analysis completed."

Automatización y scripting

Análisis de la ruta del lote

#!/bin/bash
# batch_traceroute_analysis.sh

# Configuration
TARGETS_FILE="targets.txt"
OUTPUT_DIR="traceroute_results"
REPORT_FILE="batch_traceroute_report.html"

# Create output directory
mkdir -p "$OUTPUT_DIR"

# Function to analyze single target
analyze_target() {
    local target=$1
    local output_file="$OUTPUT_DIR/${target}_$(date +%Y%m%d_%H%M%S).txt"

    echo "Analyzing route to $target..."

    # Run traceroute
    traceroute -n "$target" > "$output_file" 2>&1

    # Extract metrics
    local total_hops=$(grep -c "^ *[0-9]" "$output_file")
    local timeout_hops=$(grep -c "\*" "$output_file")
    local success_rate=$(echo "scale=2; (($total_hops - $timeout_hops) * 100) / $total_hops" | bc)

    # Calculate average end-to-end latency
    local final_latency=$(tail -1 "$output_file" | grep -oE "[0-9]+\.[0-9]+ ms" | head -1 | grep -oE "[0-9]+\.[0-9]+")

    # Return results
    echo "$target,$total_hops,$timeout_hops,$success_rate,$final_latency"
}

# Function to generate HTML report
generate_html_report() {
    local results_file=$1

    cat > "$REPORT_FILE" << EOF
<!DOCTYPE html>
<html>
<head>
    <title>Batch Traceroute Analysis Report</title>
    <style>
        body { font-family: Arial, sans-serif; margin: 20px; }
        table { border-collapse: collapse; width: 100%; }
        th, td { border: 1px solid #ddd; padding: 8px; text-align: left; }
        th { background-color: #f2f2f2; }
        .good { background-color: #d4edda; }
        .warning { background-color: #fff3cd; }
        .alert { background-color: #f8d7da; }
    </style>
</head>
<body>
    <h1>Batch Traceroute Analysis Report</h1>
    <p>Generated: $(date)</p>

    <table>
        <tr>
            <th>Target</th>
            <th>Total Hops</th>
            <th>Timeout Hops</th>
            <th>Success Rate (%)</th>
            <th>End-to-End Latency (ms)</th>
            <th>Status</th>
        </tr>
EOF

    while IFS=',' read -r target hops timeouts success_rate latency; do
        # Determine status class
        status_class="good"
        status="Good"

        if (( $(echo "$success_rate < 80" | bc -l) )); then
            status_class="alert"
            status="Poor Connectivity"
        elif (( $(echo "$latency > 200" | bc -l) )); then
            status_class="warning"
            status="High Latency"
        elif [ "$timeouts" -gt 3 ]; then
            status_class="warning"
            status="Multiple Timeouts"
        fi

        cat >> "$REPORT_FILE" << EOF
        <tr class="$status_class">
            <td>$target</td>
            <td>$hops</td>
            <td>$timeouts</td>
            <td>$success_rate</td>
            <td>$latency</td>
            <td>$status</td>
        </tr>
EOF
    done < "$results_file"

    cat >> "$REPORT_FILE" << EOF
    </table>
</body>
</html>
EOF

    echo "HTML report generated: $REPORT_FILE"
}

# Main execution
echo "Starting batch traceroute analysis..."

# Check if targets file exists
if [ ! -f "$TARGETS_FILE" ]; then
    echo "Creating sample targets file: $TARGETS_FILE"
    cat > "$TARGETS_FILE" << EOF
google.com
cloudflare.com
github.com
stackoverflow.com
reddit.com
EOF
fi

# Process each target
RESULTS_FILE="$OUTPUT_DIR/batch_results.csv"
echo "target,hops,timeouts,success_rate,latency" > "$RESULTS_FILE"

while IFS= read -r target; do
    # Skip comments and empty lines
    [[ "$target" =~ ^#.*$ ]] && continue
    [[ -z "$target" ]] && continue

    # Analyze target
    result=$(analyze_target "$target")
    echo "$result" >> "$RESULTS_FILE"

    # Small delay to avoid overwhelming network
    sleep 2
done < "$TARGETS_FILE"

# Generate reports
echo ""
echo "Analysis Summary:"
echo "=================="
column -t -s',' "$RESULTS_FILE"

generate_html_report "$RESULTS_FILE"

echo ""
echo "Batch analysis completed!"
echo "Results saved in: $OUTPUT_DIR"
echo "HTML report: $REPORT_FILE"

PowerShell Traceroute Automation

# PowerShell Traceroute Automation
# TracerouteAutomation.ps1

param(
    [string[]]$Targets = @("google.com", "cloudflare.com"),
    [string]$OutputPath = "C:\TracerouteReports",
    [int]$MaxHops = 30,
    [switch]$GenerateReport
)

# Ensure output directory exists
if (!(Test-Path $OutputPath)) {
    New-Item -ItemType Directory -Path $OutputPath -Force
}

# Function to perform enhanced traceroute
function Invoke-EnhancedTraceroute {
    param(
        [string]$Target,
        [int]$MaxHops = 30
    )

    Write-Host "Tracing route to $Target..." -ForegroundColor Green

    $result = @{
        Target = $Target
        Timestamp = Get-Date
        Hops = @()
        TotalHops = 0
        TimeoutHops = 0
        EndToEndLatency = $null
        Status = "Unknown"
    }

    try {
        # Use Test-NetConnection for traceroute
        $traceResult = Test-NetConnection -ComputerName $Target -TraceRoute -Hops $MaxHops

        if ($traceResult.TraceRoute) {
            $hopNumber = 1

            foreach ($hop in $traceResult.TraceRoute) {
                # Measure latency to this hop
                $pingResult = Test-Connection -ComputerName $hop -Count 3 -Quiet

                if ($pingResult) {
                    $latencyTest = Test-Connection -ComputerName $hop -Count 3
                    $avgLatency = ($latencyTest | Measure-Object -Property ResponseTime -Average).Average
                    $minLatency = ($latencyTest | Measure-Object -Property ResponseTime -Minimum).Minimum
                    $maxLatency = ($latencyTest | Measure-Object -Property ResponseTime -Maximum).Maximum

                    $hopData = @{
                        HopNumber = $hopNumber
                        IPAddress = $hop
                        AvgLatency = $avgLatency
                        MinLatency = $minLatency
                        MaxLatency = $maxLatency
                        Status = "Success"
                    }
                } else {
                    $hopData = @{
                        HopNumber = $hopNumber
                        IPAddress = $hop
                        AvgLatency = $null
                        MinLatency = $null
                        MaxLatency = $null
                        Status = "Timeout"
                    }
                    $result.TimeoutHops++
                }

                $result.Hops += $hopData
                $hopNumber++
            }

            $result.TotalHops = $result.Hops.Count

            # Calculate end-to-end latency
            $finalHop = $result.Hops | Where-Object { $_.Status -eq "Success" } | Select-Object -Last 1
            if ($finalHop) {
                $result.EndToEndLatency = $finalHop.AvgLatency
            }

            # Determine overall status
            $successRate = (($result.TotalHops - $result.TimeoutHops) / $result.TotalHops) * 100

            if ($successRate -ge 90 -and $result.EndToEndLatency -lt 150) {
                $result.Status = "Good"
            } elseif ($successRate -ge 70) {
                $result.Status = "Acceptable"
            } else {
                $result.Status = "Poor"
            }
        }
    }
    catch {
        Write-Error "Failed to trace route to $Target`: $_"
        $result.Status = "Failed"
    }

    return $result
}

# Function to analyze route performance
function Analyze-RoutePerformance {
    param([object]$TraceResult)

    $analysis = @{
        Target = $TraceResult.Target
        Issues = @()
        Recommendations = @()
    }

    # Check for high latency
    $highLatencyHops = $TraceResult.Hops | Where-Object { $_.AvgLatency -gt 200 }
    if ($highLatencyHops) {
        $analysis.Issues += "High latency detected at $($highLatencyHops.Count) hop(s)"
        $analysis.Recommendations += "Investigate network congestion or consider alternative routes"
    }

    # Check for timeouts
    if ($TraceResult.TimeoutHops -gt 0) {
        $analysis.Issues += "$($TraceResult.TimeoutHops) hop(s) with timeouts"
        $analysis.Recommendations += "Check for firewall filtering or rate limiting"
    }

    # Check for latency spikes
    for ($i = 1; $i -lt $TraceResult.Hops.Count; $i++) {
        $currentHop = $TraceResult.Hops[$i]
        $previousHop = $TraceResult.Hops[$i-1]

        if ($currentHop.AvgLatency -and $previousHop.AvgLatency) {
            $latencyIncrease = $currentHop.AvgLatency - $previousHop.AvgLatency

            if ($latencyIncrease -gt 100) {
                $analysis.Issues += "Significant latency increase at hop $($currentHop.HopNumber) (+$($latencyIncrease.ToString('F2'))ms)"
                $analysis.Recommendations += "Investigate bottleneck at hop $($currentHop.HopNumber) ($($currentHop.IPAddress))"
            }
        }
    }

    # Check hop count
    if ($TraceResult.TotalHops -gt 20) {
        $analysis.Issues += "High hop count ($($TraceResult.TotalHops) hops)"
        $analysis.Recommendations += "Route may not be optimal, consider using CDN or closer servers"
    }

    return $analysis
}

# Function to generate HTML report
function Generate-HTMLReport {
    param(
        [object[]]$Results,
        [string]$OutputPath
    )

    $reportFile = Join-Path $OutputPath "TracerouteReport_$(Get-Date -Format 'yyyyMMdd_HHmmss').html"

    $html = @"
<!DOCTYPE html>
<html>
<head>
    <title>Traceroute Analysis Report</title>
    <style>
        body { font-family: Arial, sans-serif; margin: 20px; }
        table { border-collapse: collapse; width: 100%; margin: 20px 0; }
        th, td { border: 1px solid #ddd; padding: 12px; text-align: left; }
        th { background-color: #f2f2f2; font-weight: bold; }
        .good { background-color: #d4edda; }
        .acceptable { background-color: #fff3cd; }
        .poor { background-color: #f8d7da; }
        .failed { background-color: #f5c6cb; }
        .summary { background-color: #e7f3ff; padding: 15px; border-radius: 5px; margin: 20px 0; }
        .hop-details { margin: 10px 0; }
        .issues { color: #721c24; }
        .recommendations { color: #155724; }
    </style>
</head>
<body>
    <h1>Traceroute Analysis Report</h1>
    <div class="summary">
        <h3>Report Summary</h3>
        <p><strong>Generated:</strong> $(Get-Date)</p>
        <p><strong>Targets Analyzed:</strong> $($Results.Count)</p>
    </div>
"@

    # Summary table
    $html += @"
    <h2>Summary Results</h2>
    <table>
        <tr>
            <th>Target</th>
            <th>Total Hops</th>
            <th>Timeout Hops</th>
            <th>End-to-End Latency (ms)</th>
            <th>Status</th>
        </tr>
"@

    foreach ($result in $Results) {
        $statusClass = $result.Status.ToLower()
        $latency = if ($result.EndToEndLatency) { $result.EndToEndLatency.ToString("F2") } else { "N/A" }

        $html += @"
        <tr class="$statusClass">
            <td>$($result.Target)</td>
            <td>$($result.TotalHops)</td>
            <td>$($result.TimeoutHops)</td>
            <td>$latency</td>
            <td>$($result.Status)</td>
        </tr>
"@
    }

    $html += "</table>"

    # Detailed analysis for each target
    $html += "<h2>Detailed Analysis</h2>"

    foreach ($result in $Results) {
        $analysis = Analyze-RoutePerformance -TraceResult $result

        $html += @"
        <h3>$($result.Target)</h3>
        <div class="hop-details">
            <h4>Route Details</h4>
            <table>
                <tr>
                    <th>Hop</th>
                    <th>IP Address</th>
                    <th>Avg Latency (ms)</th>
                    <th>Min Latency (ms)</th>
                    <th>Max Latency (ms)</th>
                    <th>Status</th>
                </tr>
"@

        foreach ($hop in $result.Hops) {
            $avgLatency = if ($hop.AvgLatency) { $hop.AvgLatency.ToString("F2") } else { "N/A" }
            $minLatency = if ($hop.MinLatency) { $hop.MinLatency.ToString("F2") } else { "N/A" }
            $maxLatency = if ($hop.MaxLatency) { $hop.MaxLatency.ToString("F2") } else { "N/A" }

            $html += @"
                <tr>
                    <td>$($hop.HopNumber)</td>
                    <td>$($hop.IPAddress)</td>
                    <td>$avgLatency</td>
                    <td>$minLatency</td>
                    <td>$maxLatency</td>
                    <td>$($hop.Status)</td>
                </tr>
"@
        }

        $html += "</table>"

        # Issues and recommendations
        if ($analysis.Issues.Count -gt 0) {
            $html += "<h4>Issues Detected</h4><ul class='issues'>"
            foreach ($issue in $analysis.Issues) {
                $html += "<li>$issue</li>"
            }
            $html += "</ul>"
        }

        if ($analysis.Recommendations.Count -gt 0) {
            $html += "<h4>Recommendations</h4><ul class='recommendations'>"
            foreach ($recommendation in $analysis.Recommendations) {
                $html += "<li>$recommendation</li>"
            }
            $html += "</ul>"
        }

        $html += "</div>"
    }

    $html += "</body></html>"

    $html | Out-File -FilePath $reportFile -Encoding UTF8
    Write-Host "HTML report generated: $reportFile" -ForegroundColor Green

    return $reportFile
}

# Main execution
Write-Host "Starting traceroute analysis for $($Targets.Count) targets..." -ForegroundColor Cyan

$results = @()

foreach ($target in $Targets) {
    $result = Invoke-EnhancedTraceroute -Target $target -MaxHops $MaxHops
    $results += $result

    # Display immediate results
    Write-Host "`nResults for $target`:" -ForegroundColor Yellow
    Write-Host "  Status: $($result.Status)"
    Write-Host "  Total Hops: $($result.TotalHops)"
    Write-Host "  Timeout Hops: $($result.TimeoutHops)"
    if ($result.EndToEndLatency) {
        Write-Host "  End-to-End Latency: $($result.EndToEndLatency.ToString('F2'))ms"
    }

    # Analyze and display issues
    $analysis = Analyze-RoutePerformance -TraceResult $result
    if ($analysis.Issues.Count -gt 0) {
        Write-Host "  Issues:" -ForegroundColor Red
        foreach ($issue in $analysis.Issues) {
            Write-Host "    - $issue" -ForegroundColor Red
        }
    }
}

# Save results to JSON
$jsonFile = Join-Path $OutputPath "TracerouteResults_$(Get-Date -Format 'yyyyMMdd_HHmmss').json"
$results | ConvertTo-Json -Depth 10 | Out-File -FilePath $jsonFile -Encoding UTF8
Write-Host "`nResults saved to: $jsonFile" -ForegroundColor Green

# Generate HTML report if requested
if ($GenerateReport) {
    $reportFile = Generate-HTMLReport -Results $results -OutputPath $OutputPath

    # Open report in default browser
    Start-Process $reportFile
}

Write-Host "`nTraceroute analysis completed!" -ForegroundColor Cyan

Solución de problemas

Problemas y soluciones comunes

# Traceroute troubleshooting guide

# 1. Permission denied errors
echo "Issue: Permission denied when using ICMP"
echo "Solution: Use sudo or switch to UDP mode"
sudo traceroute -I google.com
# or
traceroute -U google.com

# 2. Firewall blocking traceroute
echo "Issue: Firewalls blocking ICMP or UDP"
echo "Solution: Try TCP traceroute"
sudo traceroute -T -p 80 google.com
sudo traceroute -T -p 443 google.com

# 3. All hops showing asterisks
echo "Issue: All hops showing timeouts (*)"
echo "Solutions:"
echo "- Check local firewall settings"
echo "- Try different protocols (ICMP, UDP, TCP)"
echo "- Verify network connectivity"

# Test different protocols
for protocol in "-I" "-U" "-T"; do
    echo "Testing with protocol $protocol:"
    timeout 30 sudo traceroute $protocol google.com | head -5
    echo ""
done

# 4. Inconsistent results
echo "Issue: Inconsistent traceroute results"
echo "Solution: Run multiple traces and compare"

function multiple_traces() {
    local target=$1
    local count=${2:-3}

    echo "Running $count traces to $target:"
    for i in $(seq 1 $count); do
        echo "Trace $i:"
        traceroute -n "$target" | grep -E "^ *[0-9]+" | awk '{print $1 ": " $2}'
        echo ""
        sleep 2
    done
}

# 5. DNS resolution issues
echo "Issue: Slow DNS resolution affecting results"
echo "Solution: Use numeric addresses or disable DNS"

# Compare with and without DNS
echo "With DNS resolution:"
time traceroute google.com >/dev/null 2>&1

echo "Without DNS resolution:"
time traceroute -n google.com >/dev/null 2>&1

# 6. IPv6 vs IPv4 issues
echo "Issue: Different results for IPv4 vs IPv6"
echo "Solution: Test both protocols explicitly"

# Force IPv4
traceroute -4 google.com

# Force IPv6
traceroute -6 google.com

# 7. Network path changes
echo "Issue: Route changes during trace"
echo "Solution: Monitor for route stability"

function monitor_route_stability() {
    local target=$1
    local duration=${2:-300}  # 5 minutes
    local interval=${3:-30}   # 30 seconds

    echo "Monitoring route stability to $target for $duration seconds..."

    local end_time=$(($(date +%s) + duration))
    local trace_count=0

    while [ $(date +%s) -lt $end_time ]; do
        trace_count=$((trace_count + 1))
        echo "Trace $trace_count at $(date):"

        traceroute -n "$target" | grep -E "^ *[0-9]+" | awk '{print $2}' > "/tmp/route_${trace_count}.txt"

        # Compare with previous trace
        if [ $trace_count -gt 1 ]; then
            if ! diff "/tmp/route_$((trace_count-1)).txt" "/tmp/route_${trace_count}.txt" >/dev/null; then
                echo "  ⚠ Route change detected!"
                echo "  Previous route:"
                cat "/tmp/route_$((trace_count-1)).txt" | tr '\n' ' '
                echo ""
                echo "  Current route:"
                cat "/tmp/route_${trace_count}.txt" | tr '\n' ' '
                echo ""
            else
                echo "  ✓ Route stable"
            fi
        fi

        sleep $interval
    done

    # Cleanup
    rm -f /tmp/route_*.txt
}

# 8. High latency troubleshooting
function troubleshoot_high_latency() {
    local target=$1
    echo "Troubleshooting high latency to $target..."

    # Check each hop for latency issues
    traceroute -n "$target" | grep -E "^ *[0-9]+" | while read line; do
        hop=$(echo "$line" | awk '{print $1}')
        ip=$(echo "$line" | awk '{print $2}')

        if [[ "$ip" != "*" ]]; then
            # Test latency to this specific hop
            latency=$(ping -c 3 "$ip" 2>/dev/null | tail -1 | awk -F'/' '{print $5}')

            if [ -n "$latency" ]; then
                if (( $(echo "$latency > 100" | bc -l) )); then
                    echo "⚠ High latency at hop $hop ($ip): ${latency}ms"

                    # Additional diagnostics
                    echo "  Running additional tests..."

                    # Test with different packet sizes
                    for size in 64 512 1024; do
                        test_latency=$(ping -c 1 -s $size "$ip" 2>/dev/null | tail -1 | awk -F'/' '{print $5}')
                        if [ -n "$test_latency" ]; then
                            echo "    ${size} bytes: ${test_latency}ms"
                        fi
                    done
                fi
            fi
        fi
    done
}

# Example usage
# multiple_traces google.com 5
# monitor_route_stability google.com 600 60
# troubleshoot_high_latency google.com

Esta amplia hoja de trampa Traceroute proporciona todo lo necesario para el análisis profesional de rutas de red, solución de problemas de ruta y diagnóstico de red automatizado, desde operaciones básicas de localización hasta escenarios avanzados de monitoreo y automatización.