🔍 1. 测试准备阶段
1.1 环境预检
# env_check.py
import platform, socket, subprocess
def system_info():
print(f"{'='*40}")
print(f"🖥️ 系统信息".center(40))
print(f"操作系统\t{platform.system()} {platform.release()}")
print(f"主机名\t{socket.gethostname()}")
print(f"Python\t{platform.python_version()}")
def network_info():
print(f"\n{'='*40}")
print(f"🌐 网络配置".center(40))
subprocess.run(["ipconfig", "/all"] if platform.system() == "Windows" else ["ifconfig"])
system_info()
network_info
1.2 工具矩阵
工具类别 | Windows安装命令 | Linux安装命令 | 核心功能 |
---|---|---|---|
带宽测试 | choco install iperf3 | sudo apt install iperf3 | 网络吞吐量测量 |
端口扫描 | choco install nmap | sudo apt install nmap | 服务发现与漏洞检测 |
流量分析 | choco install wireshark | sudo apt install wireshark | 数据包捕获与分析 |
高级Ping | Install-Module PsPing | sudo apt install fping | 精确延迟测量 |
🧪 2. 基础测试套件
2.1 增强版Ping测试
# ping_advanced.ps1
$targets = @(
"gateway",
"114.114.114.114",
"8.8.8.8",
"www.baidu.com"
)
$results = foreach ($t in $targets) {
$ping = Test-Connection -TargetName $t -Count 10 -ErrorAction SilentlyContinue
[PSCustomObject]@{
Target = $t
AvgLatency = ($ping.ResponseTime | Measure-Object -Average).Average
PacketLoss = (10 - $ping.Count)/10*100
}
}
$results | Format-Table -AutoSize
$results | Export-Csv -Path "ping_results.csv" -NoTypeInformation
2.2 智能端口扫描
# port_scanner.py
import socket
from concurrent.futures import ThreadPoolExecutor
def scan_port(host, port):
try:
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.settimeout(2)
result = s.connect_ex((host, port))
return port, result == 0
except Exception as e:
return port, f"Error: {str(e)}"
def full_scan(host, ports=range(1, 1025)):
with ThreadPoolExecutor(max_workers=100) as executor:
results = executor.map(lambda p: scan_port(host, p), ports)
for port, status in results:
if status is True:
print(f"✅ Port {port}: OPEN")
elif "Error" not in str(status):
print(f"❌ Port {port}: CLOSED")
if __name__ == "__main__":
full_scan("target.example.com")
🚀 3. 进阶测试方案
3.1 全方位带宽压测
# bandwidth_test.sh
#!/bin/bash
SERVER_IP="192.168.1.100"
DURATION=60
THREADS=10
echo "🔄 启动iPerf3服务端..."
iperf3 -s -p 5201 &
echo "⏳ 进行TCP上行测试..."
iperf3 -c $SERVER_IP -t $DURATION -P $THREADS -J > tcp_upload.json
echo "⏳ 进行TCP下行测试..."
iperf3 -c $SERVER_IP -t $DURATION -P $THREADS -R -J > tcp_download.json
echo "⏳ 进行UDP测试..."
iperf3 -c $SERVER_IP -t $DURATION -u -b 1G -J > udp_test.json
echo "📊 生成测试报告..."
python3 generate_report.py tcp_upload.json tcp_download.json udp_test.json
pkill iperf3
3.2 智能流量分析
# 关键过滤条件库
/* 基础过滤 */
icmp || dns || tcp.port == 80 || tcp.port == 443
/* 异常检测 */
tcp.analysis.retransmission ||
tcp.analysis.duplicate_ack ||
tcp.analysis.zero_window
/* 应用层分析 */
http.request.method == "POST" ||
ssl.handshake.type == 1 ||
dns.qry.name contains "api"
🛠️ 4. 深度问题排查
4.1 网络路径诊断
# network_path.ps1
function Trace-NetworkPath {
param (
[string]$Target,
[int]$MaxHops = 30,
[int]$Timeout = 1000
)
$results = tracert -d -h $MaxHops -w $Timeout $Target |
Where-Object { $_ -match "\d+\s+ms" } |
ForEach-Object {
$parts = $_ -split "\s+"
[PSCustomObject]@{
Hop = $parts[0]
IP = $parts[-2]
Latency = $parts[-3..-1] -join "/"
}
}
$results | Export-Csv -Path "tracert_$Target.csv" -NoTypeInformation
return $results
}
Trace-NetworkPath -Target "www.example.com" -MaxHops 15
4.2 综合连接测试
# connection_test.py
import pycurl
from io import BytesIO
def test_endpoint(url):
buffer = BytesIO()
c = pycurl.Curl()
c.setopt(c.URL, url)
c.setopt(c.WRITEDATA, buffer)
c.setopt(c.TIMEOUT, 10)
metrics = {}
c.setopt(c.WRITEHEADER, lambda h: metrics.update({
'http_code': c.getinfo(c.HTTP_CODE),
'connect_time': c.getinfo(c.CONNECT_TIME),
'total_time': c.getinfo(c.TOTAL_TIME)
}))
try:
c.perform()
return {
'status': 'success',
'metrics': metrics,
'response': buffer.getvalue().decode()
}
except Exception as e:
return {
'status': 'failed',
'error': str(e)
}
finally:
c.close()
print(test_endpoint("https://www.baidu.com"))
🤖 5. 自动化运维方案
5.1 智能监控系统
# network_monitor.py
import schedule
import time
import json
from datetime import datetime
class NetworkMonitor:
def __init__(self):
self.config = self.load_config()
def load_config(self):
with open('config.json') as f:
return json.load(f)
def run_tests(self):
test_results = {}
for test in self.config['tests']:
# 执行各类测试...
test_results[test['name']] = self.execute_test(test)
self.generate_report(test_results)
def execute_test(self, test_config):
# 实现具体测试逻辑
pass
def generate_report(self, results):
filename = f"report_{datetime.now().strftime('%Y%m%d_%H%M%S')}.html"
# 生成报告...
print(f"报告已生成: {filename}")
if __name__ == "__main__":
monitor = NetworkMonitor()
schedule.every(15).minutes.do(monitor.run_tests)
while True:
schedule.run_pending()
time.sleep(1)
5.2 可视化报告模板
<!-- report_template.html -->
<!DOCTYPE html>
<html>
<head>
<title>网络测试报告 - {{ date }}</title>
<style>
.dashboard {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 20px;
}
.metric-card {
border: 1px solid #ddd;
padding: 15px;
border-radius: 5px;
}
.critical {
background-color: #ffebee;
}
</style>
</head>
<body>
<h1>网络健康报告</h1>
<div class="dashboard">
{% for test in tests %}
<div class="metric-card {% if test.status == 'critical' %}critical{% endif %}">
<h3>{{ test.name }}</h3>
<p>状态: <strong>{{ test.status }}</strong></p>
<p>延迟: {{ test.latency }} ms</p>
<p>时间: {{ test.timestamp }}</p>
</div>
{% endfor %}
</div>
</body>
</html>
🏢 6. 企业最佳实践
6.1 网络优化路线图
gantt
title 网络优化实施计划
dateFormat YYYY-MM-DD
section 第一阶段
现状评估 :a1, 2023-08-01, 7d
工具部署 :after a1, 5d
section 第二阶段
基线测试 :2023-08-15, 10d
问题修复 :2023-08-20, 14d
section 第三阶段
监控上线 :2023-09-05, 7d
团队培训 :2023-09-10, 3d
6.2 企业级检查清单
基础设施
- 核心交换机冗余配置
- 防火墙规则审计
- UPS电源测试
性能标准
- 办公网络延迟 <50ms
- 数据中心丢包率 <0.1%
- 跨境专线可用性 >99.9%
安全合规
- 网络设备固件更新
- 访问控制列表(ACL)审核
- 安全日志保留90天
📎 附录资源
A. 速查手册
# 常用诊断命令
ping -c 5 target.com # 基础连通性
mtr --report target.com # 实时路由追踪
ss -tulnp # 活动连接查看
tcpdump -i eth0 port 80 -w capture.pcap # 流量捕获
B. 技术支持
🌐 知识库: https://6v6.ren
C. 版本历史
版本 | 日期 | 更新说明 |
---|---|---|
v2.1 | 2023-07-15 | 新增自动化监控方案 |
v2.0 | 2023-06-01 | 企业级最佳实践章节 |
v1.0 | 2023-05-10 | 初始版本发布 |