v2.1.2 核心优化与多架构发布 (#561)
* feat: v2.1.0 核心重构与功能增强
## 架构重构
- 全局变量消除,迁移至 Config/State 对象
- SMB 插件融合(smb/smb2/smbghost/smbinfo)
- 服务探测重构,实现 Nmap 风格 fallback 机制
- 输出系统重构,TXT 实时刷盘 + 双写机制
- i18n 框架升级至 go-i18n
## 性能优化
- 正则表达式预编译
- 内存优化 map[string]struct{}
- 并发指纹匹配
- SOCKS5 连接复用
- 滑动窗口调度 + 自适应线程池
## 新功能
- Web 管理界面
- 多格式 POC 适配(xray/afrog)
- 增强指纹库(3139条)
- Favicon hash 指纹识别
- 插件选择性编译(Build Tags)
- fscan-lab 靶场环境
- 默认端口扩展(62→133)
## 构建系统
- 添加 no_local tag 支持排除本地插件
- 多版本构建:fscan/fscan-nolocal/fscan-web
- CI 添加 snapshot 模式支持仅测试构建
## Bug 修复
- 修复 120+ 个问题,包括 RDP panic、批量扫描漏报、
JSON 输出格式、Redis 检测、Context 超时等
## 测试增强
- 单元测试覆盖率 74-100%
- 并发安全测试
- 集成测试(Web/端口/服务/SSH/ICMP)
* fix(ci): 移除 PR 对 Project 自动化的触发
* fix: Elasticsearch未授权检测优先于爆破 (#554)
* fix: 修复RDP爆破高误报率问题 (#555)
- 移除 screen.go 中错误的认证结果覆盖逻辑
- 启用 NLA 协议的 ErrorCode 字段检测
- 添加 PubKeyAuth 验证确保认证真正成功
- 修复 io.go 中错误被静默忽略的问题
- 修复 socket.go/io.go 中可能导致 panic 的代码
- 修复 screen.go 中文件句柄泄漏和 log.Panic
* fix: 修复-user/-pwd凭据参数不生效的问题
问题原因:
- Parse()解析凭据后更新globalConfig
- 但BuildConfigFromFlags()创建新Config时使用默认字典
- 导致解析的UserPassPairs等凭据信息被丢弃
修复内容:
1. initialize.go: 将Parse解析的凭据结果应用到新Config
2. credential.go: 单用户密码对时创建UserPassPairs
3. rdp.go: 单凭据测试时跳过指纹识别,减少连接次数
* feat: RDP使用NLA仅验证模式,避免挤掉已登录用户
- 添加ErrNLAAuthSuccess标志用于NLA验证成功信号
- tpkt层支持nlaAuthOnly模式,验证成功后不建立完整会话
- x224层正确传播NLA验证结果
- rdpCrack改用NlaAuth进行凭据验证
* fix: 修复进度条在Windows终端满屏重复输出的问题
- 添加终端宽度检测,动态调整进度条长度
- 使用空格覆盖清除旧内容,避免残留
- 简化进度条格式,确保不超过终端宽度
* feat: 优化日志颜色方案,区分漏洞和普通信息
- 新增 LogVuln 级别(红色),用于漏洞和重要发现
- 密码爆破成功、未授权访问、POC漏洞等改用红色显示
- 普通信息(扫描统计等)改为白色
- Web指纹保持绿色
* refactor: 精简化输出,移除冗余启动信息
- 移除showParseSummary开局配置输出
- 移除LogPluginInfo/LogPluginInfoWithPort插件信息输出
- 移除alive_scanner冗余统计输出
- 移除port_scan_start扫描开始提示
- 移除handleUDPPorts SNMP死代码
- 移除相关i18n条目
* chore: 版本号更新为2.1.1
* fix: 降级依赖版本以保持Go 1.20兼容性
* feat(ldap): 添加NTLM Hash认证支持 (#433)
* chore: 清理无用的 replace 指令
* fix(ping): 修复 TTL expired 导致主机误判为存活的问题
在 ExecCommandPing 中增加错误关键词检测,当 ping 输出包含
TTL expired、Destination unreachable 等错误信息时,不再将
目标主机标记为存活。
Fixes #454
* fix(proxy): 修复透明代理导致输出全端口的问题
在代理初始化时主动探测代理行为,通过连接 RFC 5737 保留的
测试地址来检测是否存在"全回显"问题。如果探测到代理不可靠,
则在端口扫描时跳过所有端口,避免误报。
- 新增 proxyReliable 标志位标记代理可靠性
- 新增 ProbeProxyBehavior 函数探测代理行为
- 端口扫描前检查代理可靠性并输出警告
Fixes #495
* refactor: 移动debug模块到common/debug子包
* fix(web): 修复-u模式下Web插件未执行的问题
* fix: 优化输出格式和颜色显示
- 网段统计格式改为 10.253.0.0/16 网段存活: 26
- WebTitle基础信息改为白色,指纹识别单独绿色输出
- 移除重复的端口数量输出
* fix: URL解析自动补全协议头
-uf 文件中 192.168.1.1:8080 自动转为 http://192.168.1.1:8080
* fix: 修复-u/-uf模式下URLs丢失导致0目标扫描的问题
Parse阶段将URLs设置到全局状态,但Initialize随后创建新状态
并覆盖了全局状态,导致URLs数据丢失。现在在创建新状态前
先保存并迁移Parse阶段设置的URLs和HostPorts数据。
* fix: 智能检测HTTP/HTTPS协议并优化URL显示
- 修复-u/-uf模式URLs丢失导致0目标扫描问题
- detectProtocol改为主动TLS握手检测,不依赖服务名
- WebTitle输出显示完整协议(http/https)
- 隐藏标准端口(80/443)使输出更简洁
* refactor: 精简parsers包,统一配置构建入口
- 删除冗余的中间层(XXXInput、XXXParser类)
- 新增 config_builder.go 统一配置构建
- parsers包从3000+行精简至~540行
- 保留核心函数:ParseIP、ParsePort、文件读取、凭据解析
* test: 扩展parsers单元测试覆盖边缘情况
- 新增内网简写解析测试(192/172/10)
- 新增完整IP范围和无效CIDR测试
- 新增Windows行尾(CRLF)处理测试
- 新增凭据和哈希文件解析测试
- 新增端口解析边缘情况测试
- 测试覆盖率达到94.2%
* refactor: 优化控制台输出格式
- 去掉时间戳,保留[*][+]前缀
- Web输出合并WebTitle和WebFinger为一行
- 有指纹显示绿色[+],无指纹显示白色[*]
- 格式: code:xxx len:xxx title:xxx server:xxx [指纹]
- 服务探测格式: [Product:xxx ||Version:xxx] Banner:(xxx)
- 字段对齐,输出更清爽
* feat: 添加凭据测试未发现弱密码的提示
- credential_tester.go: 失败时设置 Type=ResultTypeCredential
- scanner.go: 根据结果类型在 error 级别输出'未发现弱密码'提示
- 新增 i18n 翻译 brute_no_weak_pass
使用 -log all 或 -log error 可看到此提示
* refactor(logging): 重构日志级别为层级过滤设计
- LogLevel 从 string 改为 int 类型,支持层级比较
- 层级设计:Debug(0) < Base(1) < Info(2) < Success(3) < Vuln(4) < Error(5)
- 设置一个级别后,显示该级别及以上的日志
- Error 级别始终显示,不会被配置过滤掉
- 保留向后兼容别名(LevelAll, LevelInfoSuccess 等)
- 更新测试以匹配新的层级过滤行为
* style(logging): Error级别日志改为黄色显示
* style(findnet): NetInfo输出改为每行一个IP
* refactor(ms17010): 优化错误提示,明确指出SMBv1不支持等情况
* fix(credential): 修复凭据测试结果不一致的问题
问题原因:
1. 未知错误类型不重试,导致服务端限流时跳过正确密码
2. SSH 错误分类不够准确,某些临时错误未被识别
修复内容:
1. 未知错误改为可重试(可能是临时问题)
2. 增加 SSH 特有的网络错误识别(handshake failed, disconnect 等)
* fix(portfinger): 修复SMB2服务指纹识别和NetInfo输出问题
- 添加SMB2ProgNeg探针支持现代Windows的SMB2协议
- 修复Go regexp对高位字节的UTF-8兼容问题,使用Latin-1转换
- 修复探针失败后连接重建逻辑
- 修复vendor_product字段名不匹配问题
- 修复NetInfo多行输出被其他日志打断的问题
* fix(config): 从默认端口移除9100,避免触发打印机打印 (#517)
* feat(proxy): 增强代理端口扫描的深度验证机制
- 新增4阶段深度验证:Banner读取→探测发送→响应等待→最终判定
- 新增SOCKS5错误码和代理错误文本检测
- 优化ProbeProxyBehavior探测逻辑,发送数据验证连接可达性
- 解决透明代理/全回显代理导致的假阳性问题
* fix(proxy): 修复代理深度验证的若干问题
- detector.go: 修复 AutoConfigureProxy 覆盖探测结果的问题
只有未探测过时才设置默认 proxyReliable 值
- port_scan.go: 改进深度验证机制
- 使用带 Host header 的 HTTP GET 请求替代 OPTIONS
- 延长响应等待超时至 2s 以适配慢速服务器
- 正确重置连接 deadline 避免影响后续操作
* refactor: 统一 common 包文件命名风格
Flag.go -> flag.go
* refactor(proxy): 删除自定义 contains() 函数,改用标准库
- 用 strings.Contains() 替代手写的 contains()
- 删除过时的注释
* fix(parsers): 修复带横杠域名被误识别为IP范围的问题
如 111-555.sss.com 这类域名因包含 - 被错误解析为 IP 范围,
添加 looksLikeIPRange() 检查,只有 - 前是有效 IP 才走范围解析
* fix(proxy): 修复代理模式下服务识别错误和端口漏扫问题
- port_scan.go: 验证通过后重建干净连接,避免HTTP GET探测污染服务识别
- port_scan.go: 优化验证策略,用轻量CRLF探测替代HTTP GET,超时从2.2s降至0.6s
- manager.go: 修正ProbeProxyBehavior判断逻辑,超时应视为代理正常转发
* fix(pool): 移除线程池预分配,优化大规模扫描内存占用
WithPreAlloc(true) 会预先创建所有 worker goroutine,
在大规模扫描(如 25域名×65535端口)时可能导致内存问题
* refactor(logging): 统一日志前缀,删除废弃的 LogBase
- 删除 LogBase 函数,所有调用迁移到 LogInfo/LogError
- 新增 PrefixDebug ([.]) 前缀,所有日志级别现在都有前缀
- 修复日志输出缩进不一致的问题
- 删除未使用的 PrefixDefault 常量
* perf(icmp): 实现自适应等待算法优化存活检测性能
- 新增 waitAdaptive 函数,监控响应增量实现智能提前结束
- 算法保守原则:最小等待1s + 连续500ms无新响应才提前结束
- 添加100ms检查间隔避免CPU空转
- 保留原有最大等待时间(3s/6s)作为兜底
- 添加完整单元测试覆盖各种场景
优化效果:
- 全部响应:~100ms (原3s)
- 无响应:~1s (原3s)
- 部分响应后稳定:~1.5s (原3s)
* perf(scan): 实现启发式优化提升扫描体验
1. 端口优先级排序:高价值端口(80,443,22,3389等)优先扫描
- 用户能更快看到有意义的结果
- 不影响端口喷洒策略
2. TCP 补充探测:ICMP 响应率<10%时自动启用
- 对未响应主机用 TCP 80/443/22/445 补充探测
- 解决防火墙过滤 ICMP 导致漏检的问题
* refactor(grdp): 精简RDP库,删除认证检测不需要的代码
- 删除 VNC 协议支持 (protocol/rfb, client/rfb.go)
- 删除完整客户端框架 (client/)
- 删除 RemoteApp 等插件 (plugin/)
- 删除 RLE 图形解压 (core/rle.go)
- 删除绘图指令处理 (pdu/orders.go, pdu/gdi.go)
- 精简 screen.go,移除截图和完整会话功能
- 移除未使用的 RGB 转换函数
grdp 代码从 13,044 行精简至 7,581 行,削减 42%
* refactor(common): 删除死代码,优化代码风格
- 删除未使用的 joinStrings/joinInts 函数
- 删除未使用的 memStats 字段和 getMemoryInfo 方法
- 简化 parsePasswords 中的循环为 append(...) 形式
* refactor(services): 统一数据库插件的DBWrapper
4个数据库插件(MySQL、PostgreSQL、MSSQL、Oracle)都有相同的sql.DB包装代码,
合并为通用的SQLDBWrapper,减少重复。
* refactor(core,grdp): 删除未使用的死代码
- 移除 BaseScanStrategy.LogPluginInfoWithPort 方法(无调用者)
- 移除 mcs.go 中被注释的旧 connect 函数实现
* refactor: 删除 deadcode 检测出的未使用函数
- proxy/detector.go: 删除 IsSOCKS5Standard, IsProxyInitialized
- findnet.go: 删除 NetworkInfo.OneLine, TreeFormat 方法
- port_scan.go: 删除 estimateScanTime 函数
- web_scanner.go: 删除 GetFingerprints 函数
- 清理相关测试代码
* refactor: 删除更多未使用的死代码
- parse.go: 删除 RemoveDuplicate 函数及其测试
- parsers.go: 删除 excludeHosts, removeDuplicates 别名函数
- 更新测试使用真正的函数名
* fix(test): 修复 TestParseIP_InvalidIPRange 测试用例
- 删除不合理的测试用例(无效IP被当作普通主机名处理是设计行为)
- 修复测试逻辑,只在真正通过时输出"正确"
* fix(scan): 移除域名预解析,保留原始域名进行扫描
域名预解析会将域名转换为IP,导致虚拟主机场景下HTTP访问失败
(Host头变成IP而非域名,无法正确路由)
* fix(scan): 修复 -hf 参数无法单独使用的问题
* fix(proxy): 修复透明代理环境下 SOCKS5 代理全端口误报问题
问题:在透明代理(TUN模式)环境下使用 SOCKS5 代理扫描时,
会出现全端口开放的误报,因为代理可靠性检测被透明代理污染。
修复方案(参考 fscanx):
1. 将探针从 CRLF 改为 HTTP GET,更有效检测真实连接状态
2. 删除 "uncertain" 状态,无响应一律判定为端口关闭
3. 调整超时时间以适应代理链路延迟
Fixes #524
* feat(telnet): 新增 telnetd RCE 命令执行验证,修复未授权访问日志级别
* fix: 修复 i18n.Tr vet 报错、Unicode 测试用例,移除过期域名
- 移除 i18n.Tr 中错误的 fmt.Sprintf fallback,消除 go vet 误报
- 修复 match_engine_test Unicode 测试用例与 Latin-1 转换逻辑不匹配
- README 移除过期的 fscan.club 域名
- 添加 .gitattributes 统一换行符为 LF
* refactor: 统一控制台输出风格,使用统一的日志函数
手动合并 PR #558 的改动,适配重构后的代码路径
* fix(ci): 修复版本注入和CI触发配置
- goreleaser ldflags 指向正确的包路径 common.version/commit/date
- version 改为 var 支持 ldflags 注入,banner 显示 commit 和构建日期
- test-build 触发分支增加 dev-* 通配
* fix(ci): 修复 Windows 产物 .exe.exe 双后缀问题
* feat(ci): 扩展构建架构支持 MIPS/ARM/FreeBSD/Solaris
@@ -0,0 +1,179 @@
|
||||
// perftest - fscan 可扩展性测试工具
|
||||
// 测量不同线程数下的扫描性能,生成 CSV 数据用于绘图
|
||||
package main
|
||||
|
||||
import (
|
||||
"encoding/csv"
|
||||
"flag"
|
||||
"fmt"
|
||||
"os"
|
||||
"os/exec"
|
||||
"regexp"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
type Result struct {
|
||||
Threads int
|
||||
Duration float64 // 秒
|
||||
PortsRate float64 // ports/sec
|
||||
FailRate float64 // 失败率%
|
||||
}
|
||||
|
||||
func main() {
|
||||
target := flag.String("target", "", "扫描目标 (如 192.168.1.0/24)")
|
||||
ports := flag.String("ports", "22,80,443,3389,8080", "端口列表")
|
||||
threads := flag.String("threads", "100,200,400,600,800,1000", "线程数列表,逗号分隔")
|
||||
repeat := flag.Int("repeat", 3, "每个线程数重复次数")
|
||||
output := flag.String("o", "perf_results.csv", "输出CSV文件")
|
||||
flag.Parse()
|
||||
|
||||
if *target == "" {
|
||||
fmt.Println("用法: perftest -target 192.168.1.0/24 [-ports 22,80,443] [-threads 100,200,400]")
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
threadList := parseIntList(*threads)
|
||||
results := []Result{}
|
||||
|
||||
fmt.Printf("=== fscan 可扩展性测试 ===\n")
|
||||
fmt.Printf("目标: %s\n", *target)
|
||||
fmt.Printf("端口: %s\n", *ports)
|
||||
fmt.Printf("线程数: %v\n", threadList)
|
||||
fmt.Printf("重复次数: %d\n\n", *repeat)
|
||||
|
||||
for _, t := range threadList {
|
||||
var totalDuration float64
|
||||
var totalRate float64
|
||||
|
||||
fmt.Printf("[线程=%d] ", t)
|
||||
for i := 0; i < *repeat; i++ {
|
||||
fmt.Printf(".")
|
||||
duration, rate := runFscan(*target, *ports, t)
|
||||
totalDuration += duration
|
||||
totalRate += rate
|
||||
}
|
||||
|
||||
avgDuration := totalDuration / float64(*repeat)
|
||||
avgRate := totalRate / float64(*repeat)
|
||||
|
||||
results = append(results, Result{
|
||||
Threads: t,
|
||||
Duration: avgDuration,
|
||||
PortsRate: avgRate,
|
||||
})
|
||||
fmt.Printf(" 平均: %.2fs, %.1f ports/sec\n", avgDuration, avgRate)
|
||||
}
|
||||
|
||||
writeCSV(*output, results)
|
||||
fmt.Printf("\n结果已保存到: %s\n", *output)
|
||||
printPlotCommand(*output)
|
||||
}
|
||||
|
||||
func runFscan(target, ports string, threads int) (duration float64, rate float64) {
|
||||
args := []string{
|
||||
"-h", target,
|
||||
"-p", ports,
|
||||
"-t", strconv.Itoa(threads),
|
||||
"-np", "-nopoc", // 禁用ping和poc,只测端口扫描
|
||||
"-o", "/dev/null",
|
||||
}
|
||||
|
||||
start := time.Now()
|
||||
cmd := exec.Command("./fscan", args...)
|
||||
output, _ := cmd.CombinedOutput()
|
||||
duration = time.Since(start).Seconds()
|
||||
|
||||
// 从输出解析扫描的端口数
|
||||
portCount := extractPortCount(string(output), target, ports)
|
||||
if duration > 0 {
|
||||
rate = float64(portCount) / duration
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func extractPortCount(output, target, ports string) int {
|
||||
// 尝试从 "扫描完成" 行提取
|
||||
re := regexp.MustCompile(`扫描完成.*?(\d+).*?端口`)
|
||||
if matches := re.FindStringSubmatch(output); len(matches) > 1 {
|
||||
count, _ := strconv.Atoi(matches[1])
|
||||
return count
|
||||
}
|
||||
|
||||
// 估算: IP数 × 端口数
|
||||
ipCount := estimateIPCount(target)
|
||||
portCount := len(strings.Split(ports, ","))
|
||||
return ipCount * portCount
|
||||
}
|
||||
|
||||
func estimateIPCount(target string) int {
|
||||
if strings.Contains(target, "/24") {
|
||||
return 254
|
||||
}
|
||||
if strings.Contains(target, "/16") {
|
||||
return 65534
|
||||
}
|
||||
return 1
|
||||
}
|
||||
|
||||
func parseIntList(s string) []int {
|
||||
parts := strings.Split(s, ",")
|
||||
result := make([]int, 0, len(parts))
|
||||
for _, p := range parts {
|
||||
if n, err := strconv.Atoi(strings.TrimSpace(p)); err == nil {
|
||||
result = append(result, n)
|
||||
}
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
func writeCSV(filename string, results []Result) {
|
||||
f, err := os.Create(filename)
|
||||
if err != nil {
|
||||
fmt.Printf("无法创建文件: %v\n", err)
|
||||
return
|
||||
}
|
||||
defer func() { _ = f.Close() }()
|
||||
|
||||
w := csv.NewWriter(f)
|
||||
_ = w.Write([]string{"threads", "duration_sec", "ports_per_sec"})
|
||||
for _, r := range results {
|
||||
_ = w.Write([]string{
|
||||
strconv.Itoa(r.Threads),
|
||||
fmt.Sprintf("%.3f", r.Duration),
|
||||
fmt.Sprintf("%.1f", r.PortsRate),
|
||||
})
|
||||
}
|
||||
w.Flush()
|
||||
}
|
||||
|
||||
func printPlotCommand(csvFile string) {
|
||||
fmt.Println("\n=== 绘图命令 ===")
|
||||
fmt.Println("\n# gnuplot:")
|
||||
fmt.Printf(`gnuplot -e "
|
||||
set terminal png size 800,600;
|
||||
set output 'scalability.png';
|
||||
set title 'fscan Scalability';
|
||||
set xlabel 'Threads';
|
||||
set ylabel 'Ports/sec';
|
||||
set grid;
|
||||
plot '%s' using 1:3 with linespoints title 'Throughput'
|
||||
"
|
||||
`, csvFile)
|
||||
|
||||
fmt.Println("\n# Python matplotlib:")
|
||||
fmt.Println(`python -c "
|
||||
import pandas as pd
|
||||
import matplotlib.pyplot as plt
|
||||
df = pd.read_csv('` + csvFile + `')
|
||||
plt.figure(figsize=(10,6))
|
||||
plt.plot(df['threads'], df['ports_per_sec'], 'o-', linewidth=2, markersize=8)
|
||||
plt.xlabel('Threads')
|
||||
plt.ylabel('Ports/sec')
|
||||
plt.title('fscan Scalability Chart')
|
||||
plt.grid(True)
|
||||
plt.savefig('scalability.png', dpi=150)
|
||||
print('已保存: scalability.png')
|
||||
"`)
|
||||
}
|
||||
@@ -0,0 +1,226 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
Go Benchmark 结果可视化脚本
|
||||
生成柱状图展示各函数的性能指标
|
||||
"""
|
||||
|
||||
import re
|
||||
import matplotlib.pyplot as plt
|
||||
import numpy as np
|
||||
import sys
|
||||
import os
|
||||
|
||||
# 设置中文字体
|
||||
plt.rcParams['font.sans-serif'] = ['Microsoft YaHei', 'SimHei', 'DejaVu Sans']
|
||||
plt.rcParams['axes.unicode_minus'] = False
|
||||
|
||||
def parse_benchmark_results(filepath):
|
||||
"""解析 Go benchmark 输出"""
|
||||
results = []
|
||||
|
||||
with open(filepath, 'r', encoding='utf-8') as f:
|
||||
for line in f:
|
||||
# 匹配格式: BenchmarkXxx-24 123456 1.234 ns/op 123 B/op 12 allocs/op
|
||||
match = re.match(
|
||||
r'(Benchmark\w+)-\d+\s+(\d+)\s+([\d.]+)\s+(ns|µs|ms)/op(?:\s+([\d.]+)\s+B/op)?(?:\s+(\d+)\s+allocs/op)?',
|
||||
line.strip()
|
||||
)
|
||||
if match:
|
||||
name = match.group(1).replace('Benchmark', '')
|
||||
ops = int(match.group(2))
|
||||
time_val = float(match.group(3))
|
||||
time_unit = match.group(4)
|
||||
bytes_op = float(match.group(5)) if match.group(5) else 0
|
||||
allocs_op = int(match.group(6)) if match.group(6) else 0
|
||||
|
||||
# 统一转换为 ns
|
||||
if time_unit == 'µs':
|
||||
time_ns = time_val * 1000
|
||||
elif time_unit == 'ms':
|
||||
time_ns = time_val * 1000000
|
||||
else:
|
||||
time_ns = time_val
|
||||
|
||||
results.append({
|
||||
'name': name,
|
||||
'ops': ops,
|
||||
'time_ns': time_ns,
|
||||
'time_val': time_val,
|
||||
'time_unit': time_unit,
|
||||
'bytes': bytes_op,
|
||||
'allocs': allocs_op
|
||||
})
|
||||
|
||||
return results
|
||||
|
||||
def format_time(ns):
|
||||
"""格式化时间显示"""
|
||||
if ns >= 1000000:
|
||||
return f"{ns/1000000:.1f}ms"
|
||||
elif ns >= 1000:
|
||||
return f"{ns/1000:.1f}µs"
|
||||
else:
|
||||
return f"{ns:.1f}ns"
|
||||
|
||||
def format_bytes(b):
|
||||
"""格式化内存显示"""
|
||||
if b >= 1024*1024:
|
||||
return f"{b/1024/1024:.1f}MB"
|
||||
elif b >= 1024:
|
||||
return f"{b/1024:.1f}KB"
|
||||
else:
|
||||
return f"{b:.0f}B"
|
||||
|
||||
def create_benchmark_charts(results, output_dir):
|
||||
"""创建 benchmark 可视化图表"""
|
||||
|
||||
if not results:
|
||||
print("没有找到 benchmark 结果")
|
||||
return
|
||||
|
||||
# 按模块分组
|
||||
core_funcs = [r for r in results if any(x in r['name'] for x in
|
||||
['CheckSum', 'TCPDial', 'ResultCollector', 'FailedPort', 'Estimate', 'Calculate', 'BuildExclude', 'ArrayCount'])]
|
||||
parser_funcs = [r for r in results if 'ParseIP' in r['name'] or 'ParsePort' in r['name']]
|
||||
finger_funcs = [r for r in results if 'DecodePattern' in r['name']]
|
||||
|
||||
# 图1: 执行时间对比 (对数刻度)
|
||||
fig, axes = plt.subplots(2, 2, figsize=(14, 10))
|
||||
fig.suptitle('Go Benchmark 性能分析', fontsize=14, fontweight='bold')
|
||||
|
||||
# 子图1: 所有函数执行时间
|
||||
ax1 = axes[0, 0]
|
||||
names = [r['name'][:20] for r in results]
|
||||
times = [r['time_ns'] for r in results]
|
||||
colors = ['#2ecc71' if t < 1000 else '#f39c12' if t < 100000 else '#e74c3c' for t in times]
|
||||
|
||||
bars = ax1.barh(names, times, color=colors)
|
||||
ax1.set_xscale('log')
|
||||
ax1.set_xlabel('执行时间 (ns, 对数刻度)')
|
||||
ax1.set_title('各函数执行时间')
|
||||
|
||||
# 添加数值标签
|
||||
for bar, t in zip(bars, times):
|
||||
ax1.text(t * 1.5, bar.get_y() + bar.get_height()/2,
|
||||
format_time(t), va='center', fontsize=8)
|
||||
|
||||
# 子图2: 内存分配
|
||||
ax2 = axes[0, 1]
|
||||
mem_results = [r for r in results if r['bytes'] > 0]
|
||||
if mem_results:
|
||||
names = [r['name'][:20] for r in mem_results]
|
||||
mem = [r['bytes'] for r in mem_results]
|
||||
colors = ['#3498db' if m < 1024 else '#9b59b6' if m < 100000 else '#e74c3c' for m in mem]
|
||||
|
||||
bars = ax2.barh(names, mem, color=colors)
|
||||
ax2.set_xscale('log')
|
||||
ax2.set_xlabel('内存分配 (B, 对数刻度)')
|
||||
ax2.set_title('各函数内存分配')
|
||||
|
||||
for bar, m in zip(bars, mem):
|
||||
ax2.text(m * 1.5, bar.get_y() + bar.get_height()/2,
|
||||
format_bytes(m), va='center', fontsize=8)
|
||||
|
||||
# 子图3: 核心模块详细对比
|
||||
ax3 = axes[1, 0]
|
||||
if core_funcs:
|
||||
names = [r['name'][:18] for r in core_funcs]
|
||||
times = [r['time_ns'] for r in core_funcs]
|
||||
|
||||
x = np.arange(len(names))
|
||||
bars = ax3.bar(x, times, color='#3498db')
|
||||
ax3.set_xticks(x)
|
||||
ax3.set_xticklabels(names, rotation=45, ha='right', fontsize=8)
|
||||
ax3.set_ylabel('执行时间 (ns)')
|
||||
ax3.set_title('核心模块 (core) 性能')
|
||||
ax3.set_yscale('log')
|
||||
|
||||
for bar, t in zip(bars, times):
|
||||
ax3.text(bar.get_x() + bar.get_width()/2, t * 1.2,
|
||||
format_time(t), ha='center', fontsize=7)
|
||||
|
||||
# 子图4: 解析器模块详细对比
|
||||
ax4 = axes[1, 1]
|
||||
if parser_funcs:
|
||||
names = [r['name'].replace('ParseIP', 'IP').replace('ParsePort', 'Port')[:15] for r in parser_funcs]
|
||||
times = [r['time_ns'] for r in parser_funcs]
|
||||
|
||||
x = np.arange(len(names))
|
||||
bars = ax4.bar(x, times, color='#e74c3c')
|
||||
ax4.set_xticks(x)
|
||||
ax4.set_xticklabels(names, rotation=45, ha='right', fontsize=8)
|
||||
ax4.set_ylabel('执行时间 (ns)')
|
||||
ax4.set_title('解析器模块 (parsers) 性能')
|
||||
ax4.set_yscale('log')
|
||||
|
||||
for bar, t in zip(bars, times):
|
||||
ax4.text(bar.get_x() + bar.get_width()/2, t * 1.2,
|
||||
format_time(t), ha='center', fontsize=7)
|
||||
|
||||
plt.tight_layout()
|
||||
|
||||
output_path = os.path.join(output_dir, 'benchmark_chart.png')
|
||||
plt.savefig(output_path, dpi=150, bbox_inches='tight')
|
||||
print(f"图表已保存: {output_path}")
|
||||
plt.close()
|
||||
|
||||
# 图2: 性能热力图 - 时间 vs 内存
|
||||
fig2, ax = plt.subplots(figsize=(10, 6))
|
||||
|
||||
# 筛选有内存分配的结果
|
||||
valid_results = [r for r in results if r['bytes'] > 0]
|
||||
if valid_results:
|
||||
times = [r['time_ns'] for r in valid_results]
|
||||
mems = [r['bytes'] for r in valid_results]
|
||||
names = [r['name'][:15] for r in valid_results]
|
||||
|
||||
scatter = ax.scatter(times, mems, s=100, c=range(len(valid_results)),
|
||||
cmap='viridis', alpha=0.7, edgecolors='black')
|
||||
|
||||
ax.set_xscale('log')
|
||||
ax.set_yscale('log')
|
||||
ax.set_xlabel('执行时间 (ns)')
|
||||
ax.set_ylabel('内存分配 (B)')
|
||||
ax.set_title('性能-内存权衡分析')
|
||||
|
||||
# 添加标签
|
||||
for i, (t, m, n) in enumerate(zip(times, mems, names)):
|
||||
ax.annotate(n, (t, m), textcoords="offset points",
|
||||
xytext=(5, 5), fontsize=7)
|
||||
|
||||
# 添加参考线
|
||||
ax.axhline(y=1024, color='orange', linestyle='--', alpha=0.5, label='1KB')
|
||||
ax.axhline(y=1024*1024, color='red', linestyle='--', alpha=0.5, label='1MB')
|
||||
ax.axvline(x=1000, color='green', linestyle='--', alpha=0.5, label='1µs')
|
||||
ax.axvline(x=1000000, color='purple', linestyle='--', alpha=0.5, label='1ms')
|
||||
ax.legend(loc='upper left', fontsize=8)
|
||||
|
||||
output_path2 = os.path.join(output_dir, 'benchmark_tradeoff.png')
|
||||
plt.savefig(output_path2, dpi=150, bbox_inches='tight')
|
||||
print(f"图表已保存: {output_path2}")
|
||||
plt.close()
|
||||
|
||||
def main():
|
||||
if len(sys.argv) < 2:
|
||||
# 默认路径
|
||||
input_file = "results/benchmarks/benchmark_results.txt"
|
||||
output_dir = "results/benchmarks"
|
||||
else:
|
||||
input_file = sys.argv[1]
|
||||
output_dir = os.path.dirname(input_file) or "."
|
||||
|
||||
if not os.path.exists(input_file):
|
||||
print(f"文件不存在: {input_file}")
|
||||
sys.exit(1)
|
||||
|
||||
print(f"解析 benchmark 结果: {input_file}")
|
||||
results = parse_benchmark_results(input_file)
|
||||
print(f"找到 {len(results)} 个 benchmark 结果")
|
||||
|
||||
for r in results:
|
||||
print(f" - {r['name']}: {format_time(r['time_ns'])}, {format_bytes(r['bytes'])}")
|
||||
|
||||
create_benchmark_charts(results, output_dir)
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,168 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
fscan 内部指标可视化脚本
|
||||
生成线程数-性能关系图
|
||||
"""
|
||||
|
||||
import csv
|
||||
import matplotlib.pyplot as plt
|
||||
import numpy as np
|
||||
import sys
|
||||
import os
|
||||
|
||||
# 设置中文字体
|
||||
plt.rcParams['font.sans-serif'] = ['Microsoft YaHei', 'SimHei', 'DejaVu Sans']
|
||||
plt.rcParams['axes.unicode_minus'] = False
|
||||
|
||||
def read_csv(filepath):
|
||||
"""读取 CSV 结果文件"""
|
||||
results = []
|
||||
with open(filepath, 'r', encoding='utf-8') as f:
|
||||
reader = csv.DictReader(f)
|
||||
for row in reader:
|
||||
results.append({
|
||||
'threads': int(row['threads']),
|
||||
'duration_ms': float(row['duration_ms']),
|
||||
'pps': float(row['packets_per_sec']),
|
||||
'total': int(row['total_packets']),
|
||||
'success': int(row['tcp_success']),
|
||||
'failed': int(row['tcp_failed']),
|
||||
'success_rate': float(row['success_rate'])
|
||||
})
|
||||
return results
|
||||
|
||||
def create_charts(results, output_dir):
|
||||
"""创建可视化图表"""
|
||||
|
||||
threads = [r['threads'] for r in results]
|
||||
pps = [r['pps'] for r in results]
|
||||
duration = [r['duration_ms']/1000 for r in results] # 转换为秒
|
||||
|
||||
# 创建 2x2 子图
|
||||
fig, axes = plt.subplots(2, 2, figsize=(12, 10))
|
||||
fig.suptitle('fscan 内部指标性能分析 (目标: 1.1.1.0/24)', fontsize=14, fontweight='bold')
|
||||
|
||||
# 子图1: 吞吐量 vs 线程数
|
||||
ax1 = axes[0, 0]
|
||||
ax1.plot(threads, pps, 'o-', color='#2ecc71', linewidth=2, markersize=8, label='实测吞吐量')
|
||||
|
||||
# 找到最优点
|
||||
max_pps_idx = np.argmax(pps)
|
||||
ax1.axvline(x=threads[max_pps_idx], color='red', linestyle='--', alpha=0.7, label=f'最优线程数: {threads[max_pps_idx]}')
|
||||
ax1.scatter([threads[max_pps_idx]], [pps[max_pps_idx]], color='red', s=150, zorder=5, marker='*')
|
||||
|
||||
ax1.set_xlabel('线程数')
|
||||
ax1.set_ylabel('吞吐量 (packets/s)')
|
||||
ax1.set_title('线程数 vs 吞吐量')
|
||||
ax1.legend()
|
||||
ax1.grid(True, alpha=0.3)
|
||||
|
||||
# 子图2: 扫描耗时 vs 线程数
|
||||
ax2 = axes[0, 1]
|
||||
ax2.plot(threads, duration, 's-', color='#e74c3c', linewidth=2, markersize=8)
|
||||
|
||||
ax2.set_xlabel('线程数')
|
||||
ax2.set_ylabel('扫描耗时 (秒)')
|
||||
ax2.set_title('线程数 vs 扫描耗时')
|
||||
ax2.grid(True, alpha=0.3)
|
||||
|
||||
# 添加耗时标签
|
||||
for t, d in zip(threads, duration):
|
||||
ax2.annotate(f'{d:.1f}s', (t, d), textcoords="offset points",
|
||||
xytext=(0, 10), ha='center', fontsize=8)
|
||||
|
||||
# 子图3: 效率分析 (吞吐量/线程数)
|
||||
ax3 = axes[1, 0]
|
||||
efficiency = [p/t*100 for p, t in zip(pps, threads)] # 每100线程的吞吐量
|
||||
ax3.bar(range(len(threads)), efficiency, color='#3498db', alpha=0.7)
|
||||
ax3.set_xticks(range(len(threads)))
|
||||
ax3.set_xticklabels(threads)
|
||||
ax3.set_xlabel('线程数')
|
||||
ax3.set_ylabel('效率 (pps/100线程)')
|
||||
ax3.set_title('线程效率分析')
|
||||
|
||||
# 添加数值标签
|
||||
for i, e in enumerate(efficiency):
|
||||
ax3.text(i, e + 0.5, f'{e:.1f}', ha='center', fontsize=9)
|
||||
|
||||
# 子图4: 加速比分析
|
||||
ax4 = axes[1, 1]
|
||||
base_pps = pps[0] # 200线程作为基准
|
||||
speedup = [p/base_pps for p in pps]
|
||||
ideal_speedup = [t/threads[0] for t in threads] # 理想线性加速
|
||||
|
||||
ax4.plot(threads, speedup, 'o-', color='#2ecc71', linewidth=2, markersize=8, label='实际加速比')
|
||||
ax4.plot(threads, ideal_speedup, '--', color='#95a5a6', linewidth=1.5, label='理想线性加速')
|
||||
|
||||
ax4.set_xlabel('线程数')
|
||||
ax4.set_ylabel('加速比 (相对于200线程)')
|
||||
ax4.set_title('可扩展性分析')
|
||||
ax4.legend()
|
||||
ax4.grid(True, alpha=0.3)
|
||||
|
||||
plt.tight_layout()
|
||||
|
||||
output_path = os.path.join(output_dir, 'internal_metrics_chart.png')
|
||||
plt.savefig(output_path, dpi=150, bbox_inches='tight')
|
||||
print(f"图表已保存: {output_path}")
|
||||
plt.close()
|
||||
|
||||
# 单独生成一张主要图表
|
||||
fig2, ax = plt.subplots(figsize=(10, 6))
|
||||
|
||||
# 双Y轴
|
||||
ax.set_xlabel('线程数', fontsize=12)
|
||||
ax.set_ylabel('吞吐量 (packets/s)', color='#2ecc71', fontsize=12)
|
||||
line1 = ax.plot(threads, pps, 'o-', color='#2ecc71', linewidth=2.5, markersize=10, label='吞吐量')
|
||||
ax.tick_params(axis='y', labelcolor='#2ecc71')
|
||||
ax.axvline(x=threads[max_pps_idx], color='red', linestyle='--', alpha=0.5)
|
||||
ax.scatter([threads[max_pps_idx]], [pps[max_pps_idx]], color='red', s=200, zorder=5, marker='*')
|
||||
|
||||
ax2 = ax.twinx()
|
||||
ax2.set_ylabel('扫描耗时 (秒)', color='#e74c3c', fontsize=12)
|
||||
line2 = ax2.plot(threads, duration, 's--', color='#e74c3c', linewidth=2, markersize=8, label='耗时')
|
||||
ax2.tick_params(axis='y', labelcolor='#e74c3c')
|
||||
|
||||
# 合并图例
|
||||
lines = line1 + line2
|
||||
labels = [l.get_label() for l in lines]
|
||||
ax.legend(lines, labels, loc='center right')
|
||||
|
||||
ax.set_title('fscan 内部指标: 线程数 vs 性能\n(目标: 1.1.1.0/24, 端口: 22,80,443,3389,8080)', fontsize=13)
|
||||
ax.grid(True, alpha=0.3)
|
||||
|
||||
# 添加最优点标注
|
||||
ax.annotate(f'最优: {threads[max_pps_idx]}线程\n{pps[max_pps_idx]:.1f} pps',
|
||||
xy=(threads[max_pps_idx], pps[max_pps_idx]),
|
||||
xytext=(threads[max_pps_idx]+200, pps[max_pps_idx]-10),
|
||||
arrowprops=dict(arrowstyle='->', color='red'),
|
||||
fontsize=10, color='red')
|
||||
|
||||
output_path2 = os.path.join(output_dir, 'scalability_chart.png')
|
||||
plt.savefig(output_path2, dpi=150, bbox_inches='tight')
|
||||
print(f"图表已保存: {output_path2}")
|
||||
plt.close()
|
||||
|
||||
def main():
|
||||
if len(sys.argv) < 2:
|
||||
input_file = "results/internal_metrics/precise_results.csv"
|
||||
output_dir = "results/internal_metrics"
|
||||
else:
|
||||
input_file = sys.argv[1]
|
||||
output_dir = os.path.dirname(input_file) or "."
|
||||
|
||||
if not os.path.exists(input_file):
|
||||
print(f"文件不存在: {input_file}")
|
||||
sys.exit(1)
|
||||
|
||||
print(f"读取数据: {input_file}")
|
||||
results = read_csv(input_file)
|
||||
print(f"找到 {len(results)} 条记录")
|
||||
|
||||
for r in results:
|
||||
print(f" 线程={r['threads']}: {r['pps']:.1f} pps, 耗时={r['duration_ms']/1000:.1f}s")
|
||||
|
||||
create_charts(results, output_dir)
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,149 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
fscan 参数测试结果可视化
|
||||
"""
|
||||
|
||||
import csv
|
||||
import matplotlib.pyplot as plt
|
||||
import numpy as np
|
||||
import os
|
||||
|
||||
# 设置中文字体
|
||||
plt.rcParams['font.sans-serif'] = ['Microsoft YaHei', 'SimHei', 'DejaVu Sans']
|
||||
plt.rcParams['axes.unicode_minus'] = False
|
||||
|
||||
def read_csv(filepath):
|
||||
results = []
|
||||
with open(filepath, 'r', encoding='utf-8') as f:
|
||||
reader = csv.DictReader(f)
|
||||
for row in reader:
|
||||
results.append(row)
|
||||
return results
|
||||
|
||||
def create_charts(output_dir):
|
||||
# 读取数据
|
||||
time_file = os.path.join(output_dir, "time_results.csv")
|
||||
mt_file = os.path.join(output_dir, "mt_results.csv")
|
||||
|
||||
time_data = read_csv(time_file)
|
||||
mt_data = read_csv(mt_file)
|
||||
|
||||
# 创建图表
|
||||
fig, axes = plt.subplots(1, 2, figsize=(14, 5))
|
||||
fig.suptitle('fscan 参数性能测试 (目标: 1.1.1.0/24)', fontsize=14, fontweight='bold')
|
||||
|
||||
# ==================== 图1: -time 超时参数 ====================
|
||||
ax1 = axes[0]
|
||||
|
||||
times = [int(d['time_seconds']) for d in time_data]
|
||||
pps = [float(d['packets_per_sec']) for d in time_data]
|
||||
duration = [float(d['duration_ms'])/1000 for d in time_data]
|
||||
|
||||
# 双Y轴
|
||||
color1 = '#2ecc71'
|
||||
ax1.set_xlabel('超时时间 -time (秒)', fontsize=11)
|
||||
ax1.set_ylabel('吞吐量 (pps)', color=color1, fontsize=11)
|
||||
bars = ax1.bar([x - 0.2 for x in range(len(times))], pps, 0.4, color=color1, alpha=0.7, label='吞吐量')
|
||||
ax1.tick_params(axis='y', labelcolor=color1)
|
||||
ax1.set_xticks(range(len(times)))
|
||||
ax1.set_xticklabels([f'{t}s' for t in times])
|
||||
|
||||
# 标注最优值
|
||||
max_idx = np.argmax(pps)
|
||||
ax1.bar(max_idx - 0.2, pps[max_idx], 0.4, color='#27ae60', alpha=0.9, edgecolor='red', linewidth=2)
|
||||
|
||||
ax1_twin = ax1.twinx()
|
||||
color2 = '#e74c3c'
|
||||
ax1_twin.set_ylabel('扫描耗时 (秒)', color=color2, fontsize=11)
|
||||
ax1_twin.bar([x + 0.2 for x in range(len(times))], duration, 0.4, color=color2, alpha=0.7, label='耗时')
|
||||
ax1_twin.tick_params(axis='y', labelcolor=color2)
|
||||
|
||||
# 添加数值标签
|
||||
for i, (p, d) in enumerate(zip(pps, duration)):
|
||||
ax1.text(i - 0.2, p + 2, f'{p:.1f}', ha='center', fontsize=9, color=color1)
|
||||
ax1_twin.text(i + 0.2, d + 0.3, f'{d:.1f}s', ha='center', fontsize=9, color=color2)
|
||||
|
||||
ax1.set_title('-time 超时参数影响\n(默认值: 3秒)', fontsize=12)
|
||||
ax1.axhline(y=pps[2], color='gray', linestyle='--', alpha=0.5, label='默认值基准')
|
||||
|
||||
# 计算相对于默认值的提升
|
||||
default_pps = pps[2] # time=3 是默认值
|
||||
improvement = [(p - default_pps) / default_pps * 100 for p in pps]
|
||||
|
||||
# ==================== 图2: -mt 模块线程参数 ====================
|
||||
ax2 = axes[1]
|
||||
|
||||
mts = [int(d['module_threads']) for d in mt_data]
|
||||
mt_pps = [float(d['packets_per_sec']) for d in mt_data]
|
||||
mt_duration = [float(d['duration_ms'])/1000 for d in mt_data]
|
||||
|
||||
ax2.bar(range(len(mts)), mt_pps, color='#3498db', alpha=0.7)
|
||||
ax2.set_xlabel('模块线程数 -mt', fontsize=11)
|
||||
ax2.set_ylabel('吞吐量 (pps)', fontsize=11)
|
||||
ax2.set_xticks(range(len(mts)))
|
||||
ax2.set_xticklabels(mts)
|
||||
ax2.set_title('-mt 模块线程参数影响\n(默认值: 20, 测试时禁用POC)', fontsize=12)
|
||||
|
||||
# 添加数值标签
|
||||
for i, p in enumerate(mt_pps):
|
||||
ax2.text(i, p + 0.5, f'{p:.1f}', ha='center', fontsize=9)
|
||||
|
||||
# 计算变化范围
|
||||
mt_range = max(mt_pps) - min(mt_pps)
|
||||
ax2.set_ylim(min(mt_pps) - 5, max(mt_pps) + 5)
|
||||
|
||||
# 添加注释
|
||||
ax2.text(0.5, 0.95, f'变化幅度: {mt_range:.2f} pps (可忽略)',
|
||||
transform=ax2.transAxes, ha='center', fontsize=10,
|
||||
bbox=dict(boxstyle='round', facecolor='wheat', alpha=0.5))
|
||||
|
||||
plt.tight_layout()
|
||||
|
||||
output_path = os.path.join(output_dir, 'param_test_chart.png')
|
||||
plt.savefig(output_path, dpi=150, bbox_inches='tight')
|
||||
print(f"图表已保存: {output_path}")
|
||||
plt.close()
|
||||
|
||||
# ==================== 生成详细分析图 ====================
|
||||
fig2, ax = plt.subplots(figsize=(10, 6))
|
||||
|
||||
x = np.arange(len(times))
|
||||
width = 0.35
|
||||
|
||||
# 性能提升百分比
|
||||
colors = ['#e74c3c' if imp < 0 else '#2ecc71' for imp in improvement]
|
||||
bars = ax.bar(x, improvement, width, color=colors, alpha=0.8)
|
||||
|
||||
ax.axhline(y=0, color='black', linestyle='-', linewidth=0.5)
|
||||
ax.set_xlabel('超时时间 -time (秒)', fontsize=12)
|
||||
ax.set_ylabel('相对默认值(3秒)的性能变化 (%)', fontsize=12)
|
||||
ax.set_title('-time 参数优化效果分析', fontsize=14, fontweight='bold')
|
||||
ax.set_xticks(x)
|
||||
ax.set_xticklabels([f'{t}s' for t in times])
|
||||
|
||||
# 添加数值标签
|
||||
for i, (bar, imp) in enumerate(zip(bars, improvement)):
|
||||
height = bar.get_height()
|
||||
ax.text(bar.get_x() + bar.get_width()/2., height + (1 if height >= 0 else -3),
|
||||
f'{imp:+.1f}%', ha='center', va='bottom' if height >= 0 else 'top',
|
||||
fontsize=11, fontweight='bold')
|
||||
|
||||
# 添加建议
|
||||
ax.text(0.02, 0.98,
|
||||
'建议:\n• 内网环境: -time 1 或 2\n• 公网环境: -time 3 (默认)\n• 高延迟网络: -time 5+',
|
||||
transform=ax.transAxes, fontsize=10, verticalalignment='top',
|
||||
bbox=dict(boxstyle='round', facecolor='lightyellow', alpha=0.8))
|
||||
|
||||
plt.tight_layout()
|
||||
|
||||
output_path2 = os.path.join(output_dir, 'time_optimization_chart.png')
|
||||
plt.savefig(output_path2, dpi=150, bbox_inches='tight')
|
||||
print(f"图表已保存: {output_path2}")
|
||||
plt.close()
|
||||
|
||||
def main():
|
||||
output_dir = "results/param_tests"
|
||||
create_charts(output_dir)
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,114 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
fscan 可扩展性图表生成工具
|
||||
|
||||
用法:
|
||||
python plot_results.py perf_results.csv
|
||||
python plot_results.py perf_results.csv -o my_chart.png
|
||||
"""
|
||||
|
||||
import sys
|
||||
import argparse
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description='绘制 fscan 可扩展性图表')
|
||||
parser.add_argument('csv_file', help='CSV 数据文件')
|
||||
parser.add_argument('-o', '--output', default='scalability.png', help='输出图片文件')
|
||||
parser.add_argument('--style', choices=['default', 'dark', 'minimal'], default='default')
|
||||
args = parser.parse_args()
|
||||
|
||||
try:
|
||||
import pandas as pd
|
||||
import matplotlib.pyplot as plt
|
||||
import matplotlib.ticker as ticker
|
||||
import matplotlib as mpl
|
||||
except ImportError:
|
||||
print("需要安装依赖: pip install pandas matplotlib")
|
||||
sys.exit(1)
|
||||
|
||||
# 设置中文字体
|
||||
plt.rcParams['font.sans-serif'] = ['Microsoft YaHei', 'SimHei', 'DejaVu Sans']
|
||||
plt.rcParams['axes.unicode_minus'] = False # 解决负号显示问题
|
||||
|
||||
# 读取数据
|
||||
df = pd.read_csv(args.csv_file)
|
||||
|
||||
# 创建图表
|
||||
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(14, 5))
|
||||
|
||||
# 样式设置
|
||||
if args.style == 'dark':
|
||||
plt.style.use('dark_background')
|
||||
color1, color2 = '#00ff88', '#ff6b6b'
|
||||
else:
|
||||
color1, color2 = '#2563eb', '#dc2626'
|
||||
|
||||
# 图1: 吞吐量 vs 线程数
|
||||
ax1.plot(df['threads'], df['ports_per_sec'], 'o-',
|
||||
color=color1, linewidth=2.5, markersize=10, label='实测吞吐量')
|
||||
|
||||
# 理想线性扩展线(以第一个点为基准)
|
||||
if len(df) > 0:
|
||||
base_rate = df['ports_per_sec'].iloc[0]
|
||||
base_threads = df['threads'].iloc[0]
|
||||
ideal = [base_rate * (t / base_threads) for t in df['threads']]
|
||||
ax1.plot(df['threads'], ideal, '--', color='gray', alpha=0.5, label='理想线性扩展')
|
||||
|
||||
ax1.set_xlabel('线程数', fontsize=12)
|
||||
ax1.set_ylabel('扫描速率 (端口/秒)', fontsize=12)
|
||||
ax1.set_title('fscan 可扩展性曲线', fontsize=14, fontweight='bold')
|
||||
ax1.grid(True, alpha=0.3)
|
||||
ax1.legend(loc='upper left')
|
||||
|
||||
# 标注峰值点
|
||||
max_idx = df['ports_per_sec'].idxmax()
|
||||
max_threads = df['threads'].iloc[max_idx]
|
||||
max_rate = df['ports_per_sec'].iloc[max_idx]
|
||||
ax1.annotate(f'峰值: {max_rate:.0f} 端口/秒\n@ {max_threads} 线程',
|
||||
xy=(max_threads, max_rate),
|
||||
xytext=(max_threads - 200, max_rate * 0.75),
|
||||
fontsize=10,
|
||||
arrowprops=dict(arrowstyle='->', color='gray'))
|
||||
|
||||
# 图2: 扫描耗时 vs 线程数
|
||||
ax2.plot(df['threads'], df['duration_sec'], 's-',
|
||||
color=color2, linewidth=2.5, markersize=10)
|
||||
|
||||
ax2.set_xlabel('线程数', fontsize=12)
|
||||
ax2.set_ylabel('扫描耗时 (秒)', fontsize=12)
|
||||
ax2.set_title('扫描耗时曲线', fontsize=14, fontweight='bold')
|
||||
ax2.grid(True, alpha=0.3)
|
||||
|
||||
# 标注最快点
|
||||
min_idx = df['duration_sec'].idxmin()
|
||||
min_threads = df['threads'].iloc[min_idx]
|
||||
min_duration = df['duration_sec'].iloc[min_idx]
|
||||
ax2.annotate(f'最快: {min_duration:.2f} 秒\n@ {min_threads} 线程',
|
||||
xy=(min_threads, min_duration),
|
||||
xytext=(min_threads - 200, min_duration * 1.5),
|
||||
fontsize=10,
|
||||
arrowprops=dict(arrowstyle='->', color='gray'))
|
||||
|
||||
plt.tight_layout()
|
||||
plt.savefig(args.output, dpi=150, bbox_inches='tight')
|
||||
print(f"图表已保存: {args.output}")
|
||||
|
||||
# 打印分析结论
|
||||
print("\n=== 分析结论 ===")
|
||||
print(f"最优线程数: {max_threads} (峰值吞吐量: {max_rate:.0f} ports/sec)")
|
||||
print(f"最短耗时: {min_duration:.2f}s @ {min_threads} 线程")
|
||||
|
||||
# 计算扩展效率
|
||||
if len(df) >= 2:
|
||||
efficiency = (df['ports_per_sec'].iloc[-1] / df['ports_per_sec'].iloc[0]) / \
|
||||
(df['threads'].iloc[-1] / df['threads'].iloc[0]) * 100
|
||||
print(f"扩展效率: {efficiency:.1f}% (相对于线性扩展)")
|
||||
|
||||
if efficiency < 50:
|
||||
print("⚠️ 扩展效率较低,可能存在锁竞争或资源瓶颈")
|
||||
elif efficiency > 80:
|
||||
print("✅ 扩展效率良好")
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
|
After Width: | Height: | Size: 252 KiB |
@@ -0,0 +1,22 @@
|
||||
BenchmarkCheckSum-24 659448997 1.821 ns/op 0 B/op 0 allocs/op
|
||||
BenchmarkArrayCountValueTop-24 4047 257006 ns/op 329822 B/op 5040 allocs/op
|
||||
BenchmarkTCPDial-24 4596 473517 ns/op 2424 B/op 27 allocs/op
|
||||
BenchmarkResultCollectorAdd-24 31689693 42.06 ns/op 99 B/op 0 allocs/op
|
||||
BenchmarkResultCollectorAddParallel-24 16319025 73.03 ns/op 99 B/op 0 allocs/op
|
||||
BenchmarkResultCollectorGetAll-24 501963 2320 ns/op 16384 B/op 1 allocs/op
|
||||
BenchmarkFailedPortCollectorAdd-24 18020209 72.26 ns/op 218 B/op 0 allocs/op
|
||||
BenchmarkEstimateScanTime-24 1000000000 0.1474 ns/op 0 B/op 0 allocs/op
|
||||
BenchmarkCalculateTotalTasks-24 345832 3346 ns/op 0 B/op 0 allocs/op
|
||||
BenchmarkBuildExcludeMap-24 8549785 143.4 ns/op 328 B/op 3 allocs/op
|
||||
ok github.com/shadow1ng/fscan/core 14.384s
|
||||
BenchmarkDecodePattern-24 23028650 44.72 ns/op 56 B/op 3 allocs/op
|
||||
BenchmarkDecodePattern_Complex-24 8355910 144.3 ns/op 40 B/op 13 allocs/op
|
||||
ok github.com/shadow1ng/fscan/core/portfinger 3.008s
|
||||
BenchmarkParseIPCIDR24-24 40768 29300 ns/op 57881 B/op 294 allocs/op
|
||||
BenchmarkParseIPCIDR16-24 829 1394559 ns/op 2692984 B/op 10122 allocs/op
|
||||
BenchmarkParseIPRange-24 42494 28765 ns/op 57816 B/op 289 allocs/op
|
||||
BenchmarkParseIPSingle-24 15086103 76.51 ns/op 64 B/op 4 allocs/op
|
||||
BenchmarkParsePortRange-24 303 4050534 ns/op 10277983 B/op 585 allocs/op
|
||||
BenchmarkParsePortList-24 1667944 700.6 ns/op 968 B/op 14 allocs/op
|
||||
BenchmarkParsePortCommon-24 1007536 1237 ns/op 1672 B/op 16 allocs/op
|
||||
ok github.com/shadow1ng/fscan/common/parsers 11.298s
|
||||
|
After Width: | Height: | Size: 74 KiB |
@@ -0,0 +1,11 @@
|
||||
"threads","duration_sec","ports_per_sec","total_ports"
|
||||
"200","30.221","42","1270"
|
||||
"400","19.124","66.4","1270"
|
||||
"600","16.162","78.6","1270"
|
||||
"800","14.099","90.1","1270"
|
||||
"1000","12.127","104.7","1270"
|
||||
"1500","12.102","104.9","1270"
|
||||
"2000","12.114","104.8","1270"
|
||||
"3000","12.122","104.8","1270"
|
||||
"4000","12.074","105.2","1270"
|
||||
"5000","12.116","104.8","1270"
|
||||
|
|
After Width: | Height: | Size: 96 KiB |
|
After Width: | Height: | Size: 166 KiB |
@@ -0,0 +1,8 @@
|
||||
"threads","duration_ms","packets_per_sec","total_packets","tcp_success","tcp_failed","success_rate"
|
||||
200,29330,43.3,1270,759,511,59.8
|
||||
400,18730,67.8,1270,759,511,59.8
|
||||
600,15270,83.2,1270,759,511,59.8
|
||||
800,13090,97.2,1270,759,511,59.8
|
||||
1000,11660,109.0,1270,759,511,59.8
|
||||
1500,11500,110.9,1270,759,511,59.8
|
||||
2000,11900,106.8,1270,759,511,59.8
|
||||
|
|
After Width: | Height: | Size: 102 KiB |
@@ -0,0 +1,6 @@
|
||||
"module_threads","duration_ms","packets_per_sec","tcp_success","tcp_failed","success_rate"
|
||||
"5","15211","83.49","759","511","59.76"
|
||||
"10","15253","83.26","759","511","59.76"
|
||||
"20","15221","83.44","759","511","59.76"
|
||||
"50","15254","83.26","759","511","59.76"
|
||||
"100","15217","83.46","759","511","59.76"
|
||||
|
|
After Width: | Height: | Size: 96 KiB |
|
After Width: | Height: | Size: 62 KiB |
@@ -0,0 +1,5 @@
|
||||
"time_seconds","duration_ms","packets_per_sec","tcp_success","tcp_failed","success_rate"
|
||||
"1","13110","96.87","759","511","59.76"
|
||||
"2","13295","95.52","759","511","59.76"
|
||||
"3","15231","83.38","759","511","59.76"
|
||||
"5","16451","77.20","759","511","59.76"
|
||||
|
@@ -0,0 +1,96 @@
|
||||
# fscan 参数性能测试脚本
|
||||
# 测试 -time 和 -mt 参数对性能的影响
|
||||
|
||||
param(
|
||||
[Parameter(Mandatory=$true)]
|
||||
[string]$Target,
|
||||
|
||||
[string]$Ports = "22,80,443,3389,8080",
|
||||
[int]$Threads = 600,
|
||||
[string]$OutputDir = "results/param_tests"
|
||||
)
|
||||
|
||||
$fscanPath = Join-Path $PSScriptRoot "..\..\fscan.exe"
|
||||
if (-not (Test-Path $fscanPath)) {
|
||||
$fscanPath = "fscan.exe"
|
||||
}
|
||||
|
||||
# 创建输出目录
|
||||
$fullOutputDir = Join-Path $PSScriptRoot $OutputDir
|
||||
New-Item -ItemType Directory -Force -Path $fullOutputDir | Out-Null
|
||||
|
||||
Write-Host "=== fscan 参数性能测试 ===" -ForegroundColor Cyan
|
||||
Write-Host "目标: $Target"
|
||||
Write-Host "端口: $Ports"
|
||||
Write-Host "基准线程: $Threads"
|
||||
Write-Host ""
|
||||
|
||||
# ==================== 测试1: -time 超时参数 ====================
|
||||
Write-Host ">>> 测试1: -time 超时参数 <<<" -ForegroundColor Yellow
|
||||
$timeValues = @(1, 2, 3, 5)
|
||||
$timeResults = @()
|
||||
|
||||
foreach ($t in $timeValues) {
|
||||
Write-Host "[time=$t] " -NoNewline
|
||||
|
||||
$output = & $fscanPath -h $Target -p $Ports -t $Threads -time $t -np -nopoc -perf -no 2>&1 | Out-String
|
||||
|
||||
if ($output -match '\[PERF_STATS_JSON\](.*?)\[/PERF_STATS_JSON\]') {
|
||||
$stats = $Matches[1] | ConvertFrom-Json
|
||||
$timeResults += [PSCustomObject]@{
|
||||
time_seconds = $t
|
||||
duration_ms = $stats.scan_duration_ms
|
||||
packets_per_sec = [math]::Round($stats.packets_per_second, 2)
|
||||
tcp_success = $stats.tcp_success
|
||||
tcp_failed = $stats.tcp_failed
|
||||
success_rate = [math]::Round($stats.success_rate, 2)
|
||||
}
|
||||
Write-Host "耗时: $([math]::Round($stats.scan_duration_ms/1000, 2))s, $([math]::Round($stats.packets_per_second, 1)) pps, 成功率: $([math]::Round($stats.success_rate, 1))%" -ForegroundColor Green
|
||||
} else {
|
||||
Write-Host "解析失败" -ForegroundColor Red
|
||||
}
|
||||
}
|
||||
|
||||
$timeResults | Export-Csv -Path (Join-Path $fullOutputDir "time_results.csv") -NoTypeInformation
|
||||
Write-Host ""
|
||||
|
||||
# ==================== 测试2: -mt 模块线程参数 ====================
|
||||
Write-Host ">>> 测试2: -mt 模块线程参数 <<<" -ForegroundColor Yellow
|
||||
$mtValues = @(5, 10, 20, 50, 100)
|
||||
$mtResults = @()
|
||||
|
||||
foreach ($mt in $mtValues) {
|
||||
Write-Host "[mt=$mt] " -NoNewline
|
||||
|
||||
# 注意: -mt 主要影响服务识别和POC,这里不用 -nopoc 来观察效果
|
||||
$output = & $fscanPath -h $Target -p $Ports -t $Threads -mt $mt -np -nopoc -perf -no 2>&1 | Out-String
|
||||
|
||||
if ($output -match '\[PERF_STATS_JSON\](.*?)\[/PERF_STATS_JSON\]') {
|
||||
$stats = $Matches[1] | ConvertFrom-Json
|
||||
$mtResults += [PSCustomObject]@{
|
||||
module_threads = $mt
|
||||
duration_ms = $stats.scan_duration_ms
|
||||
packets_per_sec = [math]::Round($stats.packets_per_second, 2)
|
||||
tcp_success = $stats.tcp_success
|
||||
tcp_failed = $stats.tcp_failed
|
||||
success_rate = [math]::Round($stats.success_rate, 2)
|
||||
}
|
||||
Write-Host "耗时: $([math]::Round($stats.scan_duration_ms/1000, 2))s, $([math]::Round($stats.packets_per_second, 1)) pps" -ForegroundColor Green
|
||||
} else {
|
||||
Write-Host "解析失败" -ForegroundColor Red
|
||||
}
|
||||
}
|
||||
|
||||
$mtResults | Export-Csv -Path (Join-Path $fullOutputDir "mt_results.csv") -NoTypeInformation
|
||||
|
||||
Write-Host ""
|
||||
Write-Host "=== 测试完成 ===" -ForegroundColor Cyan
|
||||
Write-Host "结果保存到: $fullOutputDir" -ForegroundColor Yellow
|
||||
|
||||
# 打印汇总
|
||||
Write-Host ""
|
||||
Write-Host ">>> -time 测试结果 <<<" -ForegroundColor Cyan
|
||||
$timeResults | Format-Table -AutoSize
|
||||
|
||||
Write-Host ">>> -mt 测试结果 <<<" -ForegroundColor Cyan
|
||||
$mtResults | Format-Table -AutoSize
|
||||
@@ -0,0 +1,44 @@
|
||||
@echo off
|
||||
setlocal enabledelayedexpansion
|
||||
|
||||
:: fscan 可扩展性测试脚本
|
||||
:: 用法: run_perftest.bat 192.168.1.0/24
|
||||
|
||||
set TARGET=%1
|
||||
if "%TARGET%"=="" (
|
||||
echo 用法: run_perftest.bat ^<target^>
|
||||
echo 示例: run_perftest.bat 192.168.1.0/24
|
||||
exit /b 1
|
||||
)
|
||||
|
||||
set PORTS=22,80,443,3389,8080
|
||||
set THREADS=100 200 400 600 800 1000 1500 2000
|
||||
set OUTPUT=perf_results.csv
|
||||
|
||||
echo threads,duration_sec,timestamp > %OUTPUT%
|
||||
|
||||
echo === fscan 可扩展性测试 ===
|
||||
echo 目标: %TARGET%
|
||||
echo 端口: %PORTS%
|
||||
|
||||
for %%t in (%THREADS%) do (
|
||||
echo.
|
||||
echo [测试] 线程数=%%t
|
||||
|
||||
:: 记录开始时间
|
||||
set START=%time%
|
||||
|
||||
:: 运行 fscan
|
||||
fscan.exe -h %TARGET% -p %PORTS% -t %%t -np -nopoc -o NUL 2>NUL
|
||||
|
||||
:: 记录结束时间并计算耗时
|
||||
set END=%time%
|
||||
|
||||
:: 简单输出(实际耗时需要手动计算或用 PowerShell)
|
||||
echo %%t,%START%-%END%,%date% >> %OUTPUT%
|
||||
echo 完成: %%t 线程
|
||||
)
|
||||
|
||||
echo.
|
||||
echo 结果已保存到: %OUTPUT%
|
||||
echo 使用 plot_results.py 绘图
|
||||
@@ -0,0 +1,78 @@
|
||||
# fscan 可扩展性测试 PowerShell 脚本
|
||||
# 用法: .\run_perftest.ps1 -Target 192.168.1.0/24
|
||||
|
||||
param(
|
||||
[Parameter(Mandatory=$true)]
|
||||
[string]$Target,
|
||||
|
||||
[string]$Ports = "22,80,443,3389,8080",
|
||||
[int[]]$Threads = @(100, 200, 400, 600, 800, 1000, 1500),
|
||||
[int]$Repeat = 3,
|
||||
[string]$Output = "perf_results.csv"
|
||||
)
|
||||
|
||||
$fscanPath = Join-Path $PSScriptRoot "..\..\fscan.exe"
|
||||
if (-not (Test-Path $fscanPath)) {
|
||||
$fscanPath = "fscan.exe"
|
||||
}
|
||||
|
||||
Write-Host "=== fscan 可扩展性测试 ===" -ForegroundColor Cyan
|
||||
Write-Host "目标: $Target"
|
||||
Write-Host "端口: $Ports"
|
||||
Write-Host "线程数: $($Threads -join ', ')"
|
||||
Write-Host "重复次数: $Repeat"
|
||||
Write-Host ""
|
||||
|
||||
$results = @()
|
||||
|
||||
foreach ($t in $Threads) {
|
||||
Write-Host "[线程=$t] " -NoNewline
|
||||
|
||||
$durations = @()
|
||||
|
||||
for ($i = 1; $i -le $Repeat; $i++) {
|
||||
Write-Host "." -NoNewline
|
||||
|
||||
$stopwatch = [System.Diagnostics.Stopwatch]::StartNew()
|
||||
|
||||
$proc = Start-Process -FilePath $fscanPath -ArgumentList @(
|
||||
"-h", $Target,
|
||||
"-p", $Ports,
|
||||
"-t", $t,
|
||||
"-np",
|
||||
"-nopoc",
|
||||
"-o", "NUL"
|
||||
) -NoNewWindow -Wait -PassThru
|
||||
|
||||
$stopwatch.Stop()
|
||||
$durations += $stopwatch.Elapsed.TotalSeconds
|
||||
}
|
||||
|
||||
$avgDuration = ($durations | Measure-Object -Average).Average
|
||||
|
||||
# 估算端口扫描数
|
||||
$portCount = ($Ports -split ',').Count
|
||||
if ($Target -match '/24') { $ipCount = 254 }
|
||||
elseif ($Target -match '/16') { $ipCount = 65534 }
|
||||
else { $ipCount = 1 }
|
||||
|
||||
$totalPorts = $ipCount * $portCount
|
||||
$portsPerSec = if ($avgDuration -gt 0) { $totalPorts / $avgDuration } else { 0 }
|
||||
|
||||
$results += [PSCustomObject]@{
|
||||
threads = $t
|
||||
duration_sec = [math]::Round($avgDuration, 3)
|
||||
ports_per_sec = [math]::Round($portsPerSec, 1)
|
||||
total_ports = $totalPorts
|
||||
}
|
||||
|
||||
Write-Host " 平均: $([math]::Round($avgDuration, 2))s, $([math]::Round($portsPerSec, 0)) ports/sec" -ForegroundColor Green
|
||||
}
|
||||
|
||||
# 导出 CSV
|
||||
$results | Export-Csv -Path $Output -NoTypeInformation
|
||||
Write-Host "`n结果已保存到: $Output" -ForegroundColor Yellow
|
||||
|
||||
# 打印绘图命令
|
||||
Write-Host "`n=== 绘图命令 ===" -ForegroundColor Cyan
|
||||
Write-Host "python plot_results.py $Output"
|
||||
@@ -0,0 +1,77 @@
|
||||
# fscan 精确性能测试脚本 (使用内部指标)
|
||||
# 用法: .\run_precise_test.ps1 -Target 1.1.1.0/24
|
||||
|
||||
param(
|
||||
[Parameter(Mandatory=$true)]
|
||||
[string]$Target,
|
||||
|
||||
[string]$Ports = "22,80,443,3389,8080",
|
||||
[int[]]$Threads = @(200, 400, 600, 800, 1000, 1500, 2000),
|
||||
[int]$Repeat = 1,
|
||||
[string]$Output = "precise_results.csv"
|
||||
)
|
||||
|
||||
$fscanPath = Join-Path $PSScriptRoot "..\..\fscan.exe"
|
||||
if (-not (Test-Path $fscanPath)) {
|
||||
$fscanPath = "fscan.exe"
|
||||
}
|
||||
|
||||
Write-Host "=== fscan 精确性能测试 (内部指标) ===" -ForegroundColor Cyan
|
||||
Write-Host "目标: $Target"
|
||||
Write-Host "端口: $Ports"
|
||||
Write-Host "线程数: $($Threads -join ', ')"
|
||||
Write-Host ""
|
||||
|
||||
$results = @()
|
||||
|
||||
foreach ($t in $Threads) {
|
||||
Write-Host "[线程=$t] " -NoNewline
|
||||
|
||||
$allStats = @()
|
||||
|
||||
for ($i = 1; $i -le $Repeat; $i++) {
|
||||
Write-Host "." -NoNewline
|
||||
|
||||
# 运行 fscan 并捕获输出
|
||||
$output = & $fscanPath -h $Target -p $Ports -t $t -np -nopoc -perf -no 2>&1 | Out-String
|
||||
|
||||
# 提取 JSON
|
||||
if ($output -match '\[PERF_STATS_JSON\](.*?)\[/PERF_STATS_JSON\]') {
|
||||
$jsonStr = $Matches[1]
|
||||
$stats = $jsonStr | ConvertFrom-Json
|
||||
$allStats += $stats
|
||||
}
|
||||
}
|
||||
|
||||
if ($allStats.Count -gt 0) {
|
||||
# 计算平均值
|
||||
$avgDuration = ($allStats | Measure-Object -Property scan_duration_ms -Average).Average
|
||||
$avgPPS = ($allStats | Measure-Object -Property packets_per_second -Average).Average
|
||||
$avgTotal = ($allStats | Measure-Object -Property total_packets -Average).Average
|
||||
$avgSuccess = ($allStats | Measure-Object -Property tcp_success -Average).Average
|
||||
$avgFailed = ($allStats | Measure-Object -Property tcp_failed -Average).Average
|
||||
$avgSuccessRate = ($allStats | Measure-Object -Property success_rate -Average).Average
|
||||
|
||||
$results += [PSCustomObject]@{
|
||||
threads = $t
|
||||
duration_ms = [math]::Round($avgDuration, 0)
|
||||
packets_per_sec = [math]::Round($avgPPS, 2)
|
||||
total_packets = [math]::Round($avgTotal, 0)
|
||||
tcp_success = [math]::Round($avgSuccess, 0)
|
||||
tcp_failed = [math]::Round($avgFailed, 0)
|
||||
success_rate = [math]::Round($avgSuccessRate, 2)
|
||||
}
|
||||
|
||||
Write-Host " 耗时: $([math]::Round($avgDuration/1000, 2))s, $([math]::Round($avgPPS, 1)) pkt/s, 成功率: $([math]::Round($avgSuccessRate, 1))%" -ForegroundColor Green
|
||||
} else {
|
||||
Write-Host " 解析失败" -ForegroundColor Red
|
||||
}
|
||||
}
|
||||
|
||||
# 导出 CSV
|
||||
$results | Export-Csv -Path $Output -NoTypeInformation
|
||||
Write-Host "`n结果已保存到: $Output" -ForegroundColor Yellow
|
||||
|
||||
# 打印数据表格
|
||||
Write-Host "`n=== 测试结果 ===" -ForegroundColor Cyan
|
||||
$results | Format-Table -AutoSize
|
||||