如何用脚本生成抓包分析报告

wen 实用脚本 3

使用 tshark (Wireshark 命令行工具)

#!/usr/bin/env python3
import subprocess
import json
from datetime import datetime
def analyze_pcap_with_tshark(pcap_file):
    """使用 tshark 分析 pcap 文件"""
    # 基本统计
    cmd_stats = [
        'tshark', '-r', pcap_file,
        '-q', '-z', 'io,stat,1'
    ]
    # HTTP 请求分析
    cmd_http = [
        'tshark', '-r', pcap_file,
        '-Y', 'http.request',
        '-T', 'json',
        '-e', 'http.host',
        '-e', 'http.request.uri',
        '-e', 'http.request.method'
    ]
    # 执行命令
    stats = subprocess.check_output(cmd_stats).decode()
    http_data = subprocess.check_output(cmd_http).decode()
    return stats, json.loads(http_data)
def generate_html_report(pcap_file):
    """生成 HTML 格式报告"""
    stats, http_data = analyze_pcap_with_tshark(pcap_file)
    html = f"""
    <!DOCTYPE html>
    <html>
    <head>
        <title>抓包分析报告 - {pcap_file}</title>
        <style>
            body {{ font-family: Arial, sans-serif; margin: 20px; }}
            h1 {{ color: #333; }}
            .section {{ margin: 20px 0; padding: 10px; border: 1px solid #ddd; }}
            table {{ border-collapse: collapse; width: 100%; }}
            th, td {{ border: 1px solid #ddd; padding: 8px; text-align: left; }}
            th {{ background-color: #f5f5f5; }}
        </style>
    </head>
    <body>
        <h1>抓包分析报告</h1>
        <p>生成时间: {datetime.now()}</p>
        <p>文件: {pcap_file}</p>
        <div class="section">
            <h2>流量统计</h2>
            <pre>{stats}</pre>
        </div>
        <div class="section">
            <h2>HTTP 请求</h2>
            <table>
                <tr>
                    <th>方法</th>
                    <th>主机</th>
                    <th>URI</th>
                </tr>
    """
    for packet in http_data:
        if '_source' in packet:
            layers = packet['_source']['layers']
            html += f"""
                <tr>
                    <td>{layers.get('http.request.method', [''])[0]}</td>
                    <td>{layers.get('http.host', [''])[0]}</td>
                    <td>{layers.get('http.request.uri', [''])[0]}</td>
                </tr>
            """
    html += """
            </table>
        </div>
    </body>
    </html>
    """
    with open('report.html', 'w') as f:
        f.write(html)
    print("报告已生成: report.html")
if __name__ == "__main__":
    generate_html_report("capture.pcap")

使用 Scapy (Python 库)

#!/usr/bin/env python3
from scapy.all import *
from collections import Counter
import json
class PacketAnalyzer:
    def __init__(self, pcap_file):
        self.packets = rdpcap(pcap_file)
        self.results = {}
    def analyze_basic_stats(self):
        """基本统计信息"""
        self.results['total_packets'] = len(self.packets)
        self.results['start_time'] = self.packets[0].time
        self.results['end_time'] = self.packets[-1].time
        self.results['duration'] = self.packets[-1].time - self.packets[0].time
    def analyze_protocols(self):
        """协议分析"""
        protocols = Counter()
        for pkt in self.packets:
            if IP in pkt:
                protocols['IP'] += 1
            if TCP in pkt:
                protocols['TCP'] += 1
            if UDP in pkt:
                protocols['UDP'] += 1
            if ICMP in pkt:
                protocols['ICMP'] += 1
            if HTTP in pkt:
                protocols['HTTP'] += 1
        self.results['protocols'] = dict(protocols)
    def analyze_ip_traffic(self):
        """IP 流量分析"""
        src_ips = Counter()
        dst_ips = Counter()
        for pkt in self.packets:
            if IP in pkt:
                src_ips[pkt[IP].src] += 1
                dst_ips[pkt[IP].dst] += 1
        self.results['top_sources'] = src_ips.most_common(10)
        self.results['top_destinations'] = dst_ips.most_common(10)
    def generate_report(self, output_file='analysis_report.json'):
        """生成 JSON 报告"""
        self.analyze_basic_stats()
        self.analyze_protocols()
        self.analyze_ip_traffic()
        with open(output_file, 'w') as f:
            json.dump(self.results, f, indent=2, default=str)
        print(f"报告已生成: {output_file}")
        # 同时生成可读的文本报告
        self.generate_text_report()
    def generate_text_report(self):
        """生成纯文本报告"""
        report = f"""
========================================
        抓包分析报告
========================================
基本信息:
  - 总包数: {self.results['total_packets']}
  - 持续时间: {self.results['duration']:.2f} 秒
  - 平均速率: {self.results['total_packets']/self.results['duration']:.2f} 包/秒
协议分布:
"""
        for proto, count in self.results['protocols'].items():
            report += f"  - {proto}: {count} ({count/self.results['total_packets']*100:.1f}%)\n"
        report += "\nTop 10 源IP:\n"
        for ip, count in self.results['top_sources']:
            report += f"  - {ip}: {count}\n"
        report += "\nTop 10 目标IP:\n"
        for ip, count in self.results['top_destinations']:
            report += f"  - {ip}: {count}\n"
        with open('analysis_report.txt', 'w') as f:
            f.write(report)
        print("文本报告已生成: analysis_report.txt")
if __name__ == "__main__":
    analyzer = PacketAnalyzer("capture.pcap")
    analyzer.generate_report()

高性能分析脚本 (使用 pyshark)

#!/usr/bin/env python3
import pyshark
import pandas as pd
from datetime import datetime
class AdvancedPacketAnalyzer:
    def __init__(self, pcap_file):
        self.cap = pyshark.FileCapture(pcap_file)
        self.data = []
    def extract_packet_info(self):
        """提取包信息"""
        for packet in self.cap:
            info = {
                'time': float(packet.sniff_timestamp),
                'length': int(packet.length),
                'protocol': packet.transport_layer if hasattr(packet, 'transport_layer') else 'N/A'
            }
            if hasattr(packet, 'ip'):
                info['src_ip'] = packet.ip.src
                info['dst_ip'] = packet.ip.dst
            if hasattr(packet, 'tcp'):
                info['src_port'] = packet.tcp.srcport
                info['dst_port'] = packet.tcp.dstport
                info['flags'] = packet.tcp.flags
            if hasattr(packet, 'http'):
                if hasattr(packet.http, 'request_method'):
                    info['http_method'] = packet.http.request_method
                if hasattr(packet.http, 'host'):
                    info['http_host'] = packet.http.host
                if hasattr(packet.http, 'request_uri'):
                    info['http_uri'] = packet.http.request_uri
            self.data.append(info)
    def generate_excel_report(self, output_file='analysis.xlsx'):
        """生成 Excel 报告"""
        self.extract_packet_info()
        df = pd.DataFrame(self.data)
        # 创建 Excel 写入器
        with pd.ExcelWriter(output_file, engine='openpyxl') as writer:
            # 原始数据
            df.to_excel(writer, sheet_name='Raw Data', index=False)
            # 统计信息
            stats = pd.DataFrame({
                'metric': ['Total Packets', 'Duration', 'Average Packet Length'],
                'value': [
                    len(df),
                    df['time'].max() - df['time'].min(),
                    df['length'].mean()
                ]
            })
            stats.to_excel(writer, sheet_name='Statistics', index=False)
            # 协议分布
            protocol_dist = df['protocol'].value_counts().reset_index()
            protocol_dist.columns = ['Protocol', 'Count']
            protocol_dist['Percentage'] = protocol_dist['Count'] / len(df) * 100
            protocol_dist.to_excel(writer, sheet_name='Protocol Distribution', index=False)
            # HTTP 请求
            if 'http_method' in df.columns:
                http_df = df[df['http_method'].notna()][['time', 'http_method', 'http_host', 'http_uri']]
                http_df.to_excel(writer, sheet_name='HTTP Requests', index=False)
        print(f"Excel报告已生成: {output_file}")
if __name__ == "__main__":
    analyzer = AdvancedPacketAnalyzer("capture.pcap")
    analyzer.generate_excel_report()

一键分析脚本 (综合性)

#!/bin/bash
# packet_analyzer.sh - 综合性抓包分析脚本
PCAP_FILE=$1
OUTPUT_DIR="analysis_$(date +%Y%m%d_%H%M%S)"
# 检查参数
if [ -z "$PCAP_FILE" ]; then
    echo "用法: $0 <pcap文件>"
    exit 1
fi
# 创建输出目录
mkdir -p $OUTPUT_DIR
echo "开始分析: $PCAP_FILE"
# 1. 基本信息
echo ">>> 基本信息"
capinfos $PCAP_FILE > $OUTPUT_DIR/basic_info.txt
# 2. 协议统计
echo ">>> 协议统计"
tshark -r $PCAP_FILE -q -z io,phs > $OUTPUT_DIR/protocol_stats.txt
# 3. HTTP请求分析
echo ">>> HTTP分析"
tshark -r $PCAP_FILE -Y "http.request" -T fields \
    -e frame.number \
    -e http.request.method \
    -e http.host \
    -e http.request.uri \
    -e http.user_agent \
    > $OUTPUT_DIR/http_requests.txt
# 4. 会话分析
echo ">>> 会话分析"
tshark -r $PCAP_FILE -q -z conv,tcp > $OUTPUT_DIR/tcp_conversations.txt
tshark -r $PCAP_FILE -q -z conv,udp > $OUTPUT_DIR/udp_conversations.txt
# 5. IP统计
echo ">>> IP统计"
tshark -r $PCAP_FILE -q -z ip_hosts,tree > $OUTPUT_DIR/ip_stats.txt
# 6. DNS查询
echo ">>> DNS分析"
tshark -r $PCAP_FILE -Y "dns" -T fields \
    -e dns.qry.name \
    -e dns.qry.type \
    > $OUTPUT_DIR/dns_queries.txt
# 7. 生成HTML报告
echo ">>> 生成HTML报告"
python3 << EOF
from datetime import datetime
import os
html = f"""
<!DOCTYPE html>
<html>
<head>网络抓包分析报告</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css">
</head>
<body class="container mt-4">
    <h1>网络抓包分析报告</h1>
    <p>分析时间: {datetime.now()}</p>
    <p>源文件: {os.path.basename('$PCAP_FILE')}</p>
    <div class="card mb-3">
        <div class="card-header">基本信息</div>
        <div class="card-body">
            <pre>$(cat $OUTPUT_DIR/basic_info.txt)</pre>
        </div>
    </div>
    <div class="card mb-3">
        <div class="card-header">HTTP请求统计</div>
        <div class="card-body">
            <pre>$(wc -l < $OUTPUT_DIR/http_requests.txt) 个HTTP请求</pre>
        </div>
    </div>
</body>
</html>
"""
with open('$OUTPUT_DIR/report.html', 'w') as f:
    f.write(html)
EOF
echo ""
echo "分析完成!报告目录: $OUTPUT_DIR"
echo "HTML报告: $OUTPUT_DIR/report.html"

使用说明

  1. 安装依赖:
    # tshark
    sudo apt-get install tshark

Python 库

pip install scapy pyshark pandas openpyxl

如何用脚本生成抓包分析报告


2. **运行脚本**:
```bash
# Python 脚本
python3 packet_analyzer.py
# Bash 脚本
bash packet_analyzer.sh capture.pcap
  1. 输出文件:
  • HTML/JSON/Excel 格式报告
  • 文本统计信息
  • 协议分布图

这些脚本可以根据实际需求进行定制和扩展。

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