路由追踪脚本怎写?

wen 实用脚本 39

本文目录导读:

路由追踪脚本怎写?

  1. Python路由追踪脚本
  2. Bash脚本版本(Linux)
  3. 使用说明

我来提供一个功能完整的路由追踪脚本,支持Windows和Linux系统:

Python路由追踪脚本

基本版本(跨平台)

#!/usr/bin/env python3
import subprocess
import platform
import re
import sys
def traceroute(target, max_hops=30, timeout=2):
    """
    路由追踪函数
    :param target: 目标IP或域名
    :param max_hops: 最大跳数
    :param timeout: 超时时间(秒)
    """
    system = platform.system().lower()
    # 根据系统选择命令
    if system == "windows":
        cmd = ["tracert", "-d", "-h", str(max_hops), "-w", str(timeout * 1000), target]
    else:  # Linux/Mac
        cmd = ["traceroute", "-n", "-m", str(max_hops), "-w", str(timeout), target]
    try:
        print(f"开始追踪路由到 {target}...")
        print("-" * 60)
        process = subprocess.Popen(
            cmd,
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE,
            universal_newlines=True
        )
        hop_count = 0
        for line in process.stdout:
            line = line.strip()
            if not line:
                continue
            # 解析输出
            if system == "windows":
                # 支持多版本Windows输出格式
                if re.match(r'^\s*\d+', line):
                    hop_count += 1
                    parts = re.split(r'\s+', line.strip())
                    if len(parts) >= 4:
                        hop_num = parts[0]
                        ip = parts[-1].replace('[', '').replace(']', '')
                        rtts = []
                        for p in parts[1:-1]:
                            try:
                                if '<' in p:
                                    rtts.append(f"<{p.replace('<', '').replace('ms', '').strip()}ms")
                                elif 'ms' in p:
                                    rtts.append(p)
                                else:
                                    num = int(p)
                                    rtts.append(f"{num}ms")
                            except:
                                pass
                        print(f"  {hop_num}. {ip}  {'  '.join(rtts)}")
                    else:
                        print(f"  {line}")
                elif "超时" in line or "Request timed out" in line:
                    print(f"  * * * (超时)")
            else:
                # Linux/Mac格式
                if re.match(r'^\s*\d+', line):
                    hop_count += 1
                    parts = re.split(r'\s+', line.strip())
                    if len(parts) >= 4:
                        hop_num = parts[0]
                        ip = parts[2] if len(parts) > 2 else "*"
                        rtts = []
                        for p in parts[3:]:
                            if 'ms' in p:
                                rtts.append(p)
                            elif p == '*':
                                rtts.append('*')
                        print(f"  {hop_num}. {ip}  {'  '.join(rtts[:3])}")
                    else:
                        print(f"  {line}")
        print("-" * 60)
        print(f"追踪完成,共 {hop_count} 跳")
    except FileNotFoundError:
        print("错误: 未找到traceroute命令,请安装")
        print("Ubuntu/Debian: sudo apt-get install traceroute")
        print("CentOS/RHEL: sudo yum install traceroute")
        sys.exit(1)
    except Exception as e:
        print(f"错误: {e}")
        sys.exit(1)
if __name__ == "__main__":
    if len(sys.argv) != 2:
        print("用法: python traceroute.py <目标IP或域名>")
        print("示例: python traceroute.py 8.8.8.8")
        print("      python traceroute.py www.baidu.com")
        sys.exit(1)
    target = sys.argv[1]
    traceroute(target)

高级版本(带地理信息)

#!/usr/bin/env python3
import subprocess
import platform
import re
import sys
import requests
import json
import socket
from datetime import datetime
class TracerouteAnalyzer:
    def __init__(self, target):
        self.target = target
        self.system = platform.system().lower()
        self.hops = []
    def get_geolocation(self, ip):
        """获取IP地理信息(免费API)"""
        try:
            # 使用 ip-api.com 免费API
            response = requests.get(f"http://ip-api.com/json/{ip}", timeout=3)
            if response.status_code == 200:
                data = response.json()
                if data['status'] == 'success':
                    return f"{data['city']}, {data['country']}"
        except:
            pass
        return "未知位置"
    def resolve_domain(self, ip):
        """反向解析域名"""
        try:
            host = socket.gethostbyaddr(ip)
            return host[0]
        except:
            return ip
    def run_analysis(self, max_hops=30):
        print(f"\n开始路由追踪分析: {self.target}")
        print(f"时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
        print("=" * 70)
        print(f"{'跳数':<6}{'IP地址':<20}{'响应时间':<25}{'位置':<20}")
        print("=" * 70)
        # 执行traceroute命令
        if self.system == "windows":
            cmd = ["tracert", "-d", "-h", str(max_hops), "-w", "3000", self.target]
        else:
            cmd = ["traceroute", "-n", "-m", str(max_hops), "-w", "3", "-q", "3", self.target]
        try:
            process = subprocess.Popen(
                cmd,
                stdout=subprocess.PIPE,
                stderr=subprocess.PIPE,
                universal_newlines=True,
                bufsize=1
            )
            hop_count = 0
            for line in process.stdout:
                line = line.strip()
                if not line:
                    continue
                if self.system == "windows":
                    if re.match(r'^\s*\d+', line):
                        hop_count += 1
                        parts = re.split(r'\s+', line.strip())
                        if len(parts) >= 4:
                            hop_num = parts[0]
                            ip = parts[-1].replace('[', '').replace(']', '')
                            rtts = [p for p in parts[1:-1] if 'ms' in p or '<' in p]
                            # 获取地理信息
                            location = self.get_geolocation(ip) if ip != '*' else '*'
                            hostname = self.resolve_domain(ip) if ip != '*' else ''
                            rtt_str = '  '.join(rtts[:3]) if rtts else '* * *'
                            print(f"{hop_num:<6}{ip:<20}{rtt_str:<25}{location:<20}")
                            self.hops.append({
                                'hop': hop_num,
                                'ip': ip,
                                'hostname': hostname,
                                'rtt': rtts,
                                'location': location
                            })
                else:
                    # Linux格式解析
                    if re.match(r'^\s*\d+', line):
                        hop_count += 1
                        parts = re.split(r'\s+', line.strip())
                        if len(parts) >= 4:
                            hop_num = parts[0]
                            ip = parts[2] if len(parts) > 2 else "*"
                            rtts = []
                            for p in parts[3:]:
                                if 'ms' in p:
                                    rtts.append(p)
                                elif p == '*':
                                    rtts.append('*')
                            location = self.get_geolocation(ip) if ip != '*' else ''
                            hostname = self.resolve_domain(ip) if ip != '*' else ''
                            rtt_str = '  '.join(rtts[:3]) if rtts else '* * *'
                            print(f"{hop_num:<6}{ip:<20}{rtt_str:<25}{location:<20}")
                            self.hops.append({
                                'hop': hop_num,
                                'ip': ip,
                                'hostname': hostname,
                                'rtt': rtts,
                                'location': location
                            })
            print("=" * 70)
            print(f"追踪完成,共 {hop_count} 跳")
            # 显示统计信息
            self.show_statistics()
        except FileNotFoundError:
            print("错误: 未找到traceroute命令")
            self.show_install_instructions()
        except KeyboardInterrupt:
            print("\n追踪被用户中断")
        except Exception as e:
            print(f"错误: {e}")
    def show_statistics(self):
        """显示统计信息"""
        if not self.hops:
            return
        print("\n📊 分析摘要:")
        # 找出最慢的跳点
        max_rtt = 0
        slowest_hop = None
        for hop in self.hops:
            for rtt in hop['rtt']:
                try:
                    value = float(rtt.replace('ms', '').replace('<', ''))
                    if value > max_rtt:
                        max_rtt = value
                        slowest_hop = hop
                except:
                    pass
        if slowest_hop:
            print(f"⚠️  最慢跳点: 第{slowest_hop['hop']}跳 ({slowest_hop['ip']}) - {slowest_hop['location']}")
            print(f"   最大延迟: {max_rtt}ms")
        # 显示所有跳数的位置信息
        print("\n📍 路径概览:")
        for hop in self.hops:
            print(f"  {hop['hop']:>2}. {hop['ip']:<15} -> {hop['location']}")
    def show_install_instructions(self):
        """显示安装说明"""
        print("\n请安装traceroute:")
        print("  Ubuntu/Debian: sudo apt-get install traceroute")
        print("  CentOS/RHEL:   sudo yum install traceroute")
        print("  Mac:           brew install traceroute")
def main():
    if len(sys.argv) != 2:
        print("用法: python traceroute_analyzer.py <目标IP或域名>")
        print("示例: python traceroute_analyzer.py 8.8.8.8")
        print("      python traceroute_analyzer.py www.baidu.com")
        sys.exit(1)
    target = sys.argv[1]
    analyzer = TracerouteAnalyzer(target)
    analyzer.run_analysis()
if __name__ == "__main__":
    main()

Bash脚本版本(Linux)

#!/bin/bash
# 路由追踪脚本
# 使用方法: ./traceroute.sh <目标IP或域名>
if [ $# -ne 1 ]; then
    echo "用法: $0 <目标IP或域名>"
    echo "示例: $0 8.8.8.8"
    echo "      $0 www.baidu.com"
    exit 1
fi
TARGET=$1
MAX_HOPS=30
echo "========================================"
echo "路由追踪: $TARGET"
echo "日期: $(date '+%Y-%m-%d %H:%M:%S')"
echo "========================================"
# 检查traceroute是否安装
if ! command -v traceroute &> /dev/null; then
    echo "错误: 未找到traceroute命令"
    echo "请安装: sudo apt-get install traceroute"
    exit 1
fi
# 执行路由追踪
traceroute -n -m $MAX_HOPS -w 3 -q 3 $TARGET 2>&1 | while read line; do
    echo "$line"
done
echo "========================================"
echo "追踪完成"

使用说明

安装依赖

# Python脚本需要
pip install requests
# Linux系统安装traceroute
sudo apt-get install traceroute  # Ubuntu/Debian
sudo yum install traceroute      # CentOS/RHEL

运行脚本

# Python基本版本
python traceroute.py 8.8.8.8
# Python高级版本
python traceroute_analyzer.py www.baidu.com
# Bash版本
chmod +x traceroute.sh
./traceroute.sh 8.8.8.8

这个脚本能显示每个路由节点的IP、延迟信息和地理位置,方便排查网络问题!

抱歉,评论功能暂时关闭!