使用st对png服务器进行性能测试

本文对服务器程序分别在FreeBSD和Windows(Cygwin)下进行性能测试,给出了不同环境下的测试数据,包括请求总数、并发级别、测试用时等。结果显示程序在Cygwin环境性能远低于FreeBSD环境,且st程序中的函数可能影响测试结果。

       性能测试:
    使用st对服务器程序分别在FreeBSD和windows(Cygwin)下的运行情况进行测试(st相应的运行在FreeBSD和Cygwin下)。
    机器硬件条件:Intel (R) Celeron CPU 2.40GHz;256DDR,Maxtor 80G。
        1. FreeBSD 4.7环境:
/*****************************************************/
www# ./st -n 100 -c 20 192.168.1.7/123
This is ServerTest for my pngserver, Version 1.0
Copyright (C) 2004-2005 XiongBin Xiong  All rights reserved
hustxxb@hotmail.com

testing...

Server Hostname:        192.168.1.7
Server Port:            80
Document Path:          /123

Total Requests:         100
Concurrency Level:      20
Time taken for tests:   0.709739 seconds
Complete requests:      100
Failed requests:        0
Total transferred:      35000 Bytes

Requests per second:    140.90 [#/sec] (mean)
Time per request:       141.948 [ms] (mean)
Time per request:       7.097 [ms] (mean, across all concurrent requests)
Transfer rate:          48.16 [Kbytes/sec] received

/*************************************************************/

        2. Windows XP (Cygwin)环境:
/*****************************************************/
testing...This is ServerTest for my pngserver, Version 1.0
Copyright (C) 2004-2005 XiongBin Xiong  All rights reserved
hustxxb@hotmail.com

testing...

Server Hostname: 192.168.1.7
Server Port:  80
Document Path:  /qwe

Total Requests:  50
Concurrency Level:      5
Time taken for tests:   39.487579 seconds
Complete requests:      50
Failed requests:        0
Total transferred:      7900 Bytes

Requests per second:    1.27 [#/sec] (mean)
Time per request:       3948.758 [ms] (mean)
Time per request:       789.752 [ms] (mean, across all concurrent requests)
Transfer rate:          0.20 [Kbytes/sec] received

/****************************************************/
当并发数为5时,程序正常。


/*****************************************************/
testing...This is ServerTest for my pngserver, Version 1.0
Copyright (C) 2004-2005 XiongBin Xiong  All rights reserved
hustxxb@hotmail.com

connect error
connect error
connect error
connect error
connect error
connect error
connect error


Server Hostname: 192.168.1.7
Server Port:  80
Document Path:  /qwe

Total Requests:  50
Concurrency Level:      10
Time taken for tests:   29.208741 seconds
Complete requests:      43
Failed requests:        7
Total transferred:      6794 Bytes

Requests per second:    1.47 [#/sec] (mean)
Time per request:       6792.730 [ms] (mean)
Time per request:       679.273 [ms] (mean, across all concurrent requests)
Transfer rate:          0.23 [Kbytes/sec] received

/****************************************************/
当并发数为10时,程序出现连接失败情况。


/*****************************************************/
testing...This is ServerTest for my pngserver, Version 1.0
Copyright (C) 2004-2005 XiongBin Xiong  All rights reserved
hustxxb@hotmail.com

connect error
connect error
......
connect error


Server Hostname: 192.168.1.7
Server Port:  80
Document Path:  /qwe

Total Requests:  100
Concurrency Level:      20
Time taken for tests:   30.19982 seconds
Complete requests:      54
Failed requests:        46
Total transferred:      12802 Bytes

Requests per second:    1.80 [#/sec] (mean)
Time per request:       11110.512 [ms] (mean)
Time per request:       555.926 [ms] (mean, across all concurrent requests)
Transfer rate:          0.42 [Kbytes/sec] received

/****************************************************/
当并发数为20时,程序出现大量连接失败情况。

    简单分析:
    程序运行于Cygwin环境时性能大大低于FreeBSD环境,特别是服务器程序和测试程序同时运行于Cygwin环境时;
    st程序中使用的各种函数如:strcpy,strcat,strchr,strstr等,都可能对性能造成影响,即,可能是在测试ab而不是服务器的性能。

<think>我们正在扩展网络诊断工具集,需要实现以下功能: 1. 网络连接测试(连通性) 2. 延迟测试(ping) 3. 丢包检测与统计 4. 网络速度测试(带宽测试) 5. 综合性能分析和对比 我们将使用Python标准库和第三方库(如scapy, psutil, speedtest-cli等)来实现这些功能。 注意:有些操作需要root权限(如使用scapy发送ICMP包)。 我们将分别实现每个功能,然后提供一个综合的工具类或脚本。 由于丢包检测和延迟测试通常使用ICMP(ping),我们可以使用scapy来实现,因为它可以更灵活地构建和解析数据包。 但是,我们也要考虑权限问题,因此如果用户没有权限,我们可以回退到使用系统ping命令(但这样会失去一些灵活性)。 由于用户要求内网环境,我们主要关注内网诊断。 步骤: 一、网络连接测试(连通性) 使用ICMP协议测试目标主机是否可达。 二、延迟测试 发送多个ICMP请求,计算平均往返时间(RTT)。 三、丢包检测 在延迟测试的基础上,统计发送的包和接收到的包,计算丢包率。 四、网络速度测试 我们之前已经实现了TCP带宽测试(客户端-服务器模式),这里我们可以同时使用两种方式: 1. 内网带宽测试使用我们自建的客户端-服务器模式(适合内网) 2. 外网带宽测试使用speedtest-cli(适合测试互联网速度) 五、综合性能分析和对比 将多次测试结果进行统计,生成报告,对比不同时间点的网络状况。 我们将设计一个类来封装这些功能。 注意:由于ICMP需要root权限,我们使用scapy发送ICMP包时,需要以root权限运行。 实现: 1. 连通性测试(单个目标) 2. 延迟和丢包测试(可设置发送的包数量) 3. 带宽测试(内网和公网) 另外,我们还可以考虑路由跟踪(traceroute)功能,但用户没有明确要求,这里暂不实现。 代码结构: 我们将创建一个名为NetworkDiagnostic的类,包含以下方法: - check_connectivity(host, timeout=2): 检查主机是否可达,返回布尔值 - latency_test(host, count=4, timeout=2): 测试延迟,返回平均延迟和丢包率 - bandwidth_test_internal(server_ip, port=9999, duration=10): 内网带宽测试(需要先启动服务器) - bandwidth_test_public(): 使用speedtest-cli测试公网带宽 - comprehensive_test(host, internal_server_ip=None, ...): 综合测试(包括连通性、延迟、丢包、带宽等) 由于内网带宽测试需要服务器,我们提供服务器端代码(作为类方法或单独的函数)。 我们先实现连通性、延迟和丢包检测: 使用scapy发送ICMP请求(Echo Request)并等待回复(Echo Reply)。 注意:在Linux上,如果使用scapy发送ICMP包,内核可能会自动回复,因此我们需要使用防火墙规则来阻止内核响应,或者使用其他方法。但是,对于诊断工具,我们通常不需要阻止内核响应,因为我们的目的是测试网络连通性,而不是本机。所以我们可以忽略本机对自身ping的响应,或者只测试其他主机。 另一种方法是使用系统ping命令,但这样不够灵活,而且解析输出也不方便。因此,我们选择scapy,并处理权限问题。 实现ICMP测试函数: 由于scapy的sr函数在发送ICMP请求时,可能会收到多个回复(例如重复包),我们只考虑第一个回复。 但是,对于延迟测试,我们需要发送多个包。 下面我们实现一个函数,用于发送多个ICMP请求,并收集响应时间,同时计算丢包率。 注意:Windows系统可能不允许发送原始套接字(需要管理员权限),而Linux也需要root权限。 因此,我们必须在文档中注明需要以管理员权限运行。 代码示例: 连通性测试使用ICMP):</think>### Python网络诊断工具实现方案 我将为您设计一个全面的Python网络诊断工具,涵盖连接测试、延迟分析、丢包检测、速度测试和性能对比功能。以下是完整的实现方案: ```python import socket import time import subprocess import psutil import speedtest import pandas as pd import matplotlib.pyplot as plt from scapy.all import * from concurrent.futures import ThreadPoolExecutor class NetworkDiagnostic: def __init__(self, target_ip="8.8.8.8", test_duration=10): self.target_ip = target_ip self.test_duration = test_duration self.results = {} def connection_test(self, port=80): """测试网络连接性""" try: with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock: sock.settimeout(2) result = sock.connect_ex((self.target_ip, port)) return result == 0 except Exception as e: print(f"连接测试失败: {e}") return False def latency_test(self, count=4): """测量网络延迟(ICMP Ping)""" try: cmd = ["ping", "-c", str(count), self.target_ip] output = subprocess.check_output(cmd).decode() # 解析ping结果 times = [] for line in output.split('\n'): if "time=" in line: time_str = line.split("time=")[1].split(" ")[0] times.append(float(time_str)) if not times: return None return { "min": min(times), "avg": sum(times)/len(times), "max": max(times), "loss": (1 - len(times)/count) * 100 } except Exception as e: print(f"延迟测试失败: {e}") return None def packet_loss_detection(self, count=100, interval=0.1): """高级丢包检测(使用Scapy)""" try: sent = 0 received = 0 rtt_times = [] for _ in range(count): start_time = time.time() # 发送ICMP Echo请求 response = sr1(IP(dst=self.target_ip)/ICMP(), timeout=1, verbose=0) elapsed = (time.time() - start_time) * 1000 # ms if response: received += 1 rtt_times.append(elapsed) sent += 1 time.sleep(interval) loss_rate = (1 - received/sent) * 100 return { "sent": sent, "received": received, "loss_rate": loss_rate, "avg_rtt": sum(rtt_times)/len(rtt_times) if rtt_times else 0 } except Exception as e: print(f"丢包检测失败: {e}") return None def bandwidth_test(self, duration=5): """网络带宽测试""" try: st = speedtest.Speedtest() st.get_best_server() # 并行执行下载和上传测试 with ThreadPoolExecutor() as executor: download_future = executor.submit(st.download) upload_future = executor.submit(st.upload) download_speed = download_future.result() / 1_000_000 # Mbps upload_speed = upload_future.result() / 1_000_000 # Mbps return { "download": download_speed, "upload": upload_speed, "ping": st.results.ping } except Exception as e: print(f"带宽测试失败: {e}") return None def continuous_performance_monitor(self, interval=1): """持续性能监控""" metrics = [] end_time = time.time() + self.test_duration while time.time() < end_time: # 获取网络IO统计 net_io = psutil.net_io_counters() bytes_sent = net_io.bytes_sent bytes_recv = net_io.bytes_recv # 获取延迟 latency = self.latency_test(count=1) metrics.append({ "timestamp": time.time(), "bytes_sent": bytes_sent, "bytes_recv": bytes_recv, "latency": latency["avg"] if latency else None }) time.sleep(interval) return pd.DataFrame(metrics) def run_full_diagnostic(self): """执行完整诊断套件""" print("开始网络诊断...") # 连接测试 self.results["connection"] = self.connection_test() print(f"连接测试: {'成功' if self.results['connection'] else '失败'}") # 延迟测试 self.results["latency"] = self.latency_test(count=10) print(f"延迟测试: {self.results['latency']}") # 丢包检测 self.results["packet_loss"] = self.packet_loss_detection(count=50) print(f"丢包检测: {self.results['packet_loss']}") # 带宽测试 self.results["bandwidth"] = self.bandwidth_test() print(f"带宽测试: {self.results['bandwidth']}") # 性能监控 print("启动持续性能监控...") self.results["performance"] = self.continuous_performance_monitor() print("诊断完成!") return self.results def visualize_performance(self): """可视化性能数据""" if "performance" not in self.results: print("请先运行诊断") return df = self.results["performance"] df["time"] = df["timestamp"] - df["timestamp"].min() # 计算瞬时带宽(Mbps) df["sent_mbps"] = df["bytes_sent"].diff() * 8 / 1_000_000 df["recv_mbps"] = df["bytes_recv"].diff() * 8 / 1_000_000 plt.figure(figsize=(12, 8)) # 带宽图表 plt.subplot(2, 1, 1) plt.plot(df["time"], df["sent_mbps"], label="发送带宽") plt.plot(df["time"], df["recv_mbps"], label="接收带宽") plt.title("网络带宽使用情况") plt.ylabel("带宽 (Mbps)") plt.legend() plt.grid(True) # 延迟图表 plt.subplot(2, 1, 2) plt.plot(df["time"], df["latency"], 'r-') plt.title("网络延迟变化") plt.xlabel("时间 (秒)") plt.ylabel("延迟 (ms)") plt.grid(True) plt.tight_layout() plt.savefig("network_performance.png") print("性能图表已保存为 network_performance.png") # 使用示例 if __name__ == "__main__": # 创建诊断器实例 diagnostic = NetworkDiagnostic(target_ip="192.168.1.1", test_duration=30) # 执行完整诊断 results = diagnostic.run_full_diagnostic() # 可视化结果 diagnostic.visualize_performance() # 保存完整结果 pd.DataFrame.from_dict(results, orient='index').to_csv("network_diagnostic_report.csv") print("诊断报告已保存为 network_diagnostic_report.csv") ``` ### 功能解析 #### 1. 网络连接测试 - 使用TCP连接测试目标IP和端口的可达性 - 实现原理:`socket.connect_ex()`建立TCP连接 - 返回布尔值表示连接状态 #### 2. 延迟测试 - 使用系统ping命令测量ICMP往返时间 - 计算最小、平均、最大延迟和丢包率 - 公式:$ \text{延迟} = \frac{\sum \text{RTT}}{n} $,$ \text{丢包率} = (1 - \frac{\text{接收数}}{\text{发送数}}) \times 100\% $ #### 3. 丢包检测 - 使用Scapy发送定制ICMP请求 - 精确统计发送/接收包数量和丢包率 - 测量每次请求的RTT时间 #### 4. 带宽测试 - 集成speedtest-cli测量下载/上传速度 - 使用线程池并行执行测试 - 结果转换为Mbps单位 #### 5. 性能监控与分析 - 持续收集网络IO和延迟数据 - 计算瞬时带宽:$ \text{带宽} = \frac{\Delta \text{字节} \times 8}{\Delta \text{时间}} $ - 使用Matplotlib生成可视化图表 #### 6. 综合诊断 - 集成所有测试项的统一接口 - 生成CSV格式诊断报告 - 可视化性能趋势图 ### 技术要点 1. **权限要求**: - ICMP测试需要root权限(Linux/Mac使用`sudo`) ```bash sudo python network_diagnostic.py ``` 2. **依赖安装**: ```bash pip install scapy pandas matplotlib speedtest-cli psutil ``` 3. **诊断报告示例**: | 测试类型 | 指标 | 值 | |---------------|-------------|----------| | 连接测试 | 状态 | 成功 | | 延迟测试 | 平均延迟 | 24.3 ms | | 丢包检测 | 丢包率 | 0.8% | | 带宽测试 | 下载速度 | 85.2 Mbps| 4. **性能优化**: - 使用线程池并行执行带宽测试 - Scapy超时设置避免阻塞 - Pandas高效处理时间序列数据 ### 应用场景 1. **网络故障排查**:快速定位连接问题 2. **服务质量监测**:定期执行诊断生成报告 3. **网络优化验证**:对比优化前后的性能数据 4. **容量规划**:分析带宽使用趋势预测需求 ### 扩展建议 1. **网络拓扑集成**:结合nmap扫描绘制拓扑图 2. **历史数据分析**:存储多次诊断结果进行趋势分析 3. **告警系统**:当丢包率或延迟超过阈值时触发通知 4. **Web界面**:使用Flask/Django创建可视化仪表盘
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值