Tshark抓包脚本
in Cisco with 0 comment
Tshark抓包脚本
in Cisco with 0 comment

抓包脚本,方便快速抓包

抓包过滤有如下两个格式:

快速抓单目标

#!/bin/bash

iface="enp1s0"
path="/data"

# 创建目录(如果不存在)
mkdir -p "$path"

# 获取当前时间戳
timestamp=$(date +%Y-%m-%d-%H:%M:%S)

# 读取用户输入
read -p "请输入要抓包的主机或网段 (如 192.168.1.1 或 192.168.0.0/24): " host

# 判断输入是否为空
if [ -z "$host" ]; then
    echo "抓包目标不能为空"
    exit 1
fi

# 构建过滤器
if [[ "$host" =~ / ]]; then
    filter="net $host"
else
    filter="host $host"
fi

# 将斜杠替换为下划线防止文件名出错
safe_host="${host//\//_}"
file="$path/${timestamp}-${safe_host}.pcapng"

echo "开始抓包,使用接口 $iface,过滤条件: $filter"
tshark -i "$iface" -f "$filter" -w "$file"

echo "抓包完成,文件已保存为:$file"

# 是否转换为可阅读文本
read -p "是否转换为txt文本便于AI分析?(y/n, 默认 y): " answer
answer=${answer:-y}

if [[ "$answer" == "y" || "$answer" == "Y" ]]; then
    txt_file="$path/${timestamp}-${safe_host}.txt"
    echo "正在转换格式,请不要操作!"
    tshark -r "$file" \
        -T fields \
        -E header=y \
        -e frame.number \
        -e frame.time_relative \
        -e ip.src \
        -e ip.dst \
        -e tcp.srcport \
        -e tcp.dstport \
        -e _ws.col.Info > "$txt_file"
    echo "已转换为文本:$txt_file"
fi

交互抓包

#!/bin/bash

# 抓包输出目录
output_dir="/data"
mkdir -p "$output_dir"

# 显示可用网卡
echo "=== 可用网卡列表 ==="
tshark -D
echo "==================="

# 选择网卡
read -p "请输入要抓包的网卡编号(例如 1): " iface_num
iface=$(tshark -D | sed -n "${iface_num}p" | cut -d. -f2- | sed 's/^[[:space:]]*//')

if [ -z "$iface" ]; then
    echo "❌ 无效的网卡编号,退出。"
    exit 1
fi

# 输入主机或网段
read -p "请输入抓包目标(IP或CIDR网段,例如 192.168.1.1 或 192.168.0.0/24): " target

if [ -z "$target" ]; then
    echo "❌ 抓包目标不能为空"
    exit 1
fi

# 判断过滤器类型
if [[ "$target" =~ / ]]; then
    filter="net $target"
else
    filter="host $target"
fi

# 选填:抓包持续时间
read -p "是否限制抓包时长?输入秒数(如 30),留空表示手动 Ctrl+C 停止: " duration

# 安全命名(去掉斜线)
timestamp=$(date +%Y-%m-%d-%H-%M-%S)
safe_target="${target//\//_}"
pcap_file="${output_dir}/${timestamp}-${safe_target}.pcapng"

echo "✅ 开始抓包,接口: $iface,过滤: $filter"
if [ -n "$duration" ]; then
    tshark -i "$iface" -f "$filter" -a duration:$duration -w "$pcap_file"
else
    tshark -i "$iface" -f "$filter" -w "$pcap_file"
fi

echo "✅ 抓包完成,文件保存为: $pcap_file"

# 是否导出为 txt
read -p "是否转换为txt文本供AI分析?(y/n, 默认 y): " convert
convert=${convert:-y}

if [[ "$convert" =~ ^[Yy]$ ]]; then
    txt_file="${output_dir}/${timestamp}-${safe_target}.txt"
    tshark -r "$pcap_file" \
        -T fields \
        -E header=y \
        -e frame.number \
        -e frame.time_relative \
        -e ip.src \
        -e ip.dst \
        -e tcp.srcport \
        -e tcp.dstport \
        -e _ws.col.Info > "$txt_file"
    echo "✅ 转换完成,文本保存为: $txt_file"
fi

交互同时抓多目标

#!/bin/bash

output_dir="/data"
mkdir -p "$output_dir"

# 显示网卡
echo "=== 可用网卡列表 ==="
tshark -D
echo "==================="

read -p "请输入要抓包的网卡编号: " iface_num
iface=$(tshark -D | sed -n "${iface_num}p" | cut -d. -f2- | sed 's/^[[:space:]]*//')
[ -z "$iface" ] && echo "无效网卡编号" && exit 1

read -p "请输入多个抓包目标(用空格分隔,如 192.168.1.1 192.168.0.0/24): " -a targets
[ ${#targets[@]} -eq 0 ] && echo "目标不能为空" && exit 1

read -p "是否限制抓包时长?输入秒数(默认无限制): " duration

for target in "${targets[@]}"; do
    if [[ "$target" =~ / ]]; then
        filter="net $target"
    else
        filter="host $target"
    fi

    timestamp=$(date +%Y-%m-%d-%H-%M-%S)
    safe_target="${target//\//_}"
    pcap_file="${output_dir}/${timestamp}-${safe_target}.pcapng"

    echo "▶ 正在抓包 $target"
    if [ -n "$duration" ]; then
        tshark -i "$iface" -f "$filter" -a duration:$duration -w "$pcap_file"
    else
        tshark -i "$iface" -f "$filter" -w "$pcap_file"
    fi
    echo "✅ 已保存到 $pcap_file"
done

web控制抓单目标

from flask import Flask, render_template_string, request
import subprocess
import os
from datetime import datetime

app = Flask(__name__)
OUTPUT_DIR = "/data"
os.makedirs(OUTPUT_DIR, exist_ok=True)

TEMPLATE = """
<!doctype html>
<title>抓包控制台</title>
<h2>Web 抓包控制台</h2>
<form method="post">
    网卡名: <input name="iface" value="enp1s0"><br><br>
    抓包目标(IP 或 网段): <input name="target"><br><br>
    抓包时长(秒,可选): <input name="duration"><br><br>
    <input type="submit" value="开始抓包">
</form>
{% if msg %}<p style="color:green">{{ msg }}</p>{% endif %}
"""

@app.route("/", methods=["GET", "POST"])
def index():
    msg = ""
    if request.method == "POST":
        iface = request.form["iface"]
        target = request.form["target"]
        duration = request.form.get("duration")
        if "/" in target:
            f = f"net {target}"
        else:
            f = f"host {target}"
        timestamp = datetime.now().strftime("%Y-%m-%d-%H-%M-%S")
        safe_target = target.replace("/", "_")
        pcap_path = os.path.join(OUTPUT_DIR, f"{timestamp}-{safe_target}.pcapng")
        cmd = ["tshark", "-i", iface, "-f", f, "-w", pcap_path]
        if duration:
            cmd += ["-a", f"duration:{duration}"]
        subprocess.Popen(cmd)
        msg = f"抓包已启动,保存为:{pcap_path}"
    return render_template_string(TEMPLATE, msg=msg)

if __name__ == "__main__":
    app.run(host="0.0.0.0", port=8888)

web控制抓多目标

from flask import Flask, render_template_string, request
import subprocess
import os
from datetime import datetime

app = Flask(__name__)
OUTPUT_DIR = "/data"
os.makedirs(OUTPUT_DIR, exist_ok=True)

TEMPLATE = """
<!doctype html>
<title>多目标抓包平台</title>
<h2>Web 多目标抓包平台</h2>
<form method="post">
    网卡名: <input name="iface" value="enp1s0"><br><br>
    抓包目标(可多个,用空格分隔): <input name="targets"><br><br>
    抓包时长(秒,可选): <input name="duration"><br><br>
    <input type="submit" value="开始抓包">
</form>
{% if msg %}<p style="color:green;white-space:pre-line;">{{ msg }}</p>{% endif %}
"""

@app.route("/", methods=["GET", "POST"])
def index():
    msg = ""
    if request.method == "POST":
        iface = request.form["iface"]
        targets = request.form["targets"].split()
        duration = request.form.get("duration")

        for target in targets:
            if "/" in target:
                f = f"net {target}"
            else:
                f = f"host {target}"
            timestamp = datetime.now().strftime("%Y-%m-%d-%H-%M-%S")
            safe_target = target.replace("/", "_")
            pcap_path = os.path.join(OUTPUT_DIR, f"{timestamp}-{safe_target}.pcapng")
            cmd = ["tshark", "-i", iface, "-f", f, "-w", pcap_path]
            if duration:
                cmd += ["-a", f"duration:{duration}"]
            subprocess.Popen(cmd)
            msg += f"✅ {target} 抓包启动,保存为 {pcap_path}\n"

    return render_template_string(TEMPLATE, msg=msg)

if __name__ == "__main__":
    app.run(host="0.0.0.0", port=8888)

web优化

The article has been posted for too long and comments have been automatically closed.