基于vue的电子期刊投稿系统[vue]-计算机毕业设计源码+LW文档
2026/4/23 13:21:44
import subprocess import time import json import re TARGET_IP = "改成设备ip" PING_COUNT = 1000 TIMEOUT = 1000 # ms STUTTER_THRESHOLD = 100 # ms latencies = [] packet_loss = 0 stutter_count = 0 def ping_once(ip): try: result = subprocess.run( ["ping", "-n", "1", "-w", str(TIMEOUT), ip], capture_output=True, text=True, encoding="gbk", # 关键修复点(Windows) errors="ignore" ) output = result.stdout # 判断是否成功(关键) if "TTL=" not in output and "ttl=" not in output.lower(): return None # 兼容多种格式: # time=1ms / time<1ms / 时间=1ms match = re.search(r"(?:time|时间)[=<]\s*(\d+)\s*ms", output, re.IGNORECASE) if match: return int(match.group(1)) # 处理 time<1ms 情况(Windows 特殊) if "time<1ms" in output or "时间<1ms" in output: return 1 return 0 # 有 TTL 但没解析到时间(极低延迟) except Exception: return None print(f"Start ping {TARGET_IP} x {PING_COUNT}...\n") start_time = time.time() for i in range(PING_COUNT): latency = ping_once(TARGET_IP) if latency is None: packet_loss += 1 print(f"[{i+1}] Timeout") else: latencies.append(latency) if latency > STUTTER_THRESHOLD: stutter_count += 1 print(f"[{i+1}] {latency} ms") end_time = time.time() # 统计 total_sent = PING_COUNT total_received = len(latencies) loss_rate = (packet_loss / total_sent) * 100 avg_latency = sum(latencies) / len(latencies) if latencies else 0 max_latency = max(latencies) if latencies else 0 min_latency = min(latencies) if latencies else 0 stutter_rate = (stutter_count / total_sent) * 100 result = { "target_ip": TARGET_IP, "total_sent": total_sent, "total_received": total_received, "packet_loss": packet_loss, "packet_loss_rate (%)": round(loss_rate, 2), "latency": { "avg_ms": round(avg_latency, 2), "max_ms": max_latency, "min_ms": min_latency }, "stutter": { "threshold_ms": STUTTER_THRESHOLD, "count": stutter_count, "rate (%)": round(stutter_rate, 2) }, "test_duration_sec": round(end_time - start_time, 2) } with open("ping_result.json", "w", encoding="utf-8") as f: json.dump(result, f, indent=4, ensure_ascii=False) print("\n=== 测试完成 ===") print(json.dumps(result, indent=4, ensure_ascii=False)) print("\n结果已保存到 ping_result.json")运行此脚本代码,可以自动ping1000次并保留json文件进行统计延迟率等信息