自动ping值脚本
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_outputTrue, textTrue, encodinggbk, # 关键修复点Windows errorsignore ) output result.stdout # 判断是否成功关键 if TTL not in output and ttl not in output.lower(): return None # 兼容多种格式 # time1ms / time1ms / 时间1ms match re.search(r(?:time|时间)[]\s*(\d)\s*ms, output, re.IGNORECASE) if match: return int(match.group(1)) # 处理 time1ms 情况Windows 特殊 if time1ms in output or 时间1ms in output: return 1 return 0 # 有 TTL 但没解析到时间极低延迟 except Exception: return None print(fStart 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[{i1}] Timeout) else: latencies.append(latency) if latency STUTTER_THRESHOLD: stutter_count 1 print(f[{i1}] {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, encodingutf-8) as f: json.dump(result, f, indent4, ensure_asciiFalse) print(\n 测试完成 ) print(json.dumps(result, indent4, ensure_asciiFalse)) print(\n结果已保存到 ping_result.json)运行此脚本代码可以自动ping1000次并保留json文件进行统计延迟率等信息
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/2546231.html
如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!