下面是一个用于检测网络断流和丢包的脚本,使用Python编写,基于ping命令进行网络连通性测试:

#!/usr/bin/env python3
"""
网络断流丢包检测工具
功能:
1. 持续ping目标地址
2. 检测连续丢包(断流)
3. 统计实时丢包率
4. 记录断流事件和时间戳
"""
import os
import sys
import time
import subprocess
import platform
from datetime import datetime
# 配置参数
TARGET = "8.8.8.8" # 默认检测地址 (Google DNS)
INTERVAL = 1 # ping间隔(秒)
CONTINUOUS_LIMIT = 3 # 连续丢包次数阈值(视为断流)
LOG_FILE = "network_monitor.log" # 日志文件路径
def ping_host(host):
"""执行ping命令并返回结果"""
param = "-n 1" if platform.system().lower() == "windows" else "-c 1"
command = ["ping", param, "-w", "1000", host]
try:
response = subprocess.run(command,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
text=True)
return response.returncode == 0
except Exception:
return False
def main():
# 初始化计数器
total_count = 0
success_count = 0
continuous_fail = 0
outage_start = None
print(f"开始网络监控,目标: {TARGET},按Ctrl+C停止...")
print(f"{'时间':<20} | {'状态':<8} | {'连续丢包':<10} | {'丢包率':<8} | 事件")
try:
while True:
total_count += 1
timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
# 执行ping测试
if ping_host(TARGET):
status = "成功"
success_count += 1
# 断流恢复检测
if continuous_fail >= CONTINUOUS_LIMIT:
outage_duration = round(time.time() - outage_start, 1)
event = f"⚠️ 网络恢复! 断流时长: {outage_duration}秒"
print(f"
