You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

编写工具脚本从ping日志中统计停机时长的技术需求

Ping日志解析与停机时长统计脚本开发方案

Got it, let's tackle this problem of parsing ping logs to calculate total downtime. First, let's clarify the key points we need to handle:

需求梳理

Your ping log shows successful responses, but we also need to account for failure entries (like Request timeout for icmp_seq=XXX or Destination Host Unreachable) since those are what indicate downtime. The core goal is to:

  • Track when connectivity drops and resumes
  • Calculate the duration of each outage
  • Sum up the total downtime, plus show detailed outage windows for transparency

实现思路

  1. Parse timestamps: Convert the log's timestamp format (Mar 25 00:07:13) into a machine-readable datetime object for accurate duration calculations.
  2. Classify log lines: Identify which lines are successful pings and which are failures.
  3. Track outage states: Keep track of when an outage starts, then calculate the duration once connectivity is restored.
  4. Aggregate results: Sum all individual outage durations and output a clear, human-readable summary.

示例Python脚本

Here's a ready-to-use script that handles this logic. It's flexible enough to adapt to most standard ping log formats:

import datetime
from datetime import timedelta

def analyze_ping_log(log_file_path):
    outage_start = None
    total_downtime = timedelta(0)
    outage_records = []

    with open(log_file_path, 'r') as f:
        for line_num, line in enumerate(f, 1):
            line = line.strip()
            if not line:
                continue

            # Extract timestamp (first 15 characters: e.g., "Mar 25 00:07:13")
            try:
                timestamp_str = line[:15]
                current_time = datetime.datetime.strptime(timestamp_str, "%b %d %H:%M:%S")
                # Note: If your log includes the year, add "%Y" to the format string (e.g., "%b %d %Y %H:%M:%S")
            except ValueError:
                print(f"Warning: Could not parse timestamp on line {line_num}: {line}")
                continue

            # Check if this is a successful ping
            if "64 bytes from" in line or "bytes from" in line:
                if outage_start is not None:
                    # Outage just ended
                    outage_duration = current_time - outage_start
                    total_downtime += outage_duration
                    outage_records.append({
                        "start": outage_start.strftime("%b %d %H:%M:%S"),
                        "end": current_time.strftime("%b %d %H:%M:%S"),
                        "duration": str(outage_duration)
                    })
                    outage_start = None
            else:
                # This is a failure; start tracking if not already
                if outage_start is None:
                    outage_start = current_time

        # Handle case where log ends during an outage
        if outage_start is not None:
            outage_records.append({
                "start": outage_start.strftime("%b %d %H:%M:%S"),
                "end": "Log ended (outage ongoing)",
                "duration": "Unknown (ongoing)"
            })

    # Print results
    print("=== Ping Log Downtime Analysis ===")
    print(f"Total Downtime: {total_downtime}")
    print("\nIndividual Outage Records:")
    for idx, outage in enumerate(outage_records, 1):
        print(f"Outage {idx}:")
        print(f"  Start: {outage['start']}")
        print(f"  End: {outage['end']}")
        print(f"  Duration: {outage['duration']}\n")

if __name__ == "__main__":
    import sys
    if len(sys.argv) != 2:
        print("Usage: python ping_downtime_analyzer.py <path_to_ping_log>")
        sys.exit(1)
    analyze_ping_log(sys.argv[1])

使用说明

  1. Save the script: Save it as ping_downtime_analyzer.py
  2. Run it: Pass your ping log file as an argument:
    python ping_downtime_analyzer.py your_ping_log.txt
    
  3. Customize if needed:
    • If your log includes the year, update the timestamp format to "%b %d %Y %H:%M:%S"
    • Adjust the success/failure detection strings if your ping output uses different wording (e.g., Reply from on Windows systems)

关键细节说明

  • The script handles partial outages (where the log ends mid-outage) by flagging it as ongoing.
  • It skips empty lines and warns about unparseable lines so you can clean up your log if needed.
  • All duration calculations use Python's timedelta for precise time arithmetic, avoiding manual math errors.

内容的提问来源于stack exchange,提问作者Wajahat

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 07:55:25