2025年6月15日日曜日

Windows環境 pythonでのPing統計 試行するも課題あり

某所で例示してもらったスクリプト


import csv

import subprocess

import tkinter as tk

from tkinter import filedialog

from datetime import datetime

import os


def ping(ip, log_lines):

    success_count = 0

    log_lines.append(f"\n=== Ping開始: {ip} ===")

    for i in range(3):

        cmd = ["ping", "-n", "1", "-w", "200", ip]

        result = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)

        if result.returncode == 0:

            success_count += 1

        log_lines.append(f"\n-- Try {i+1} --")

        log_lines.append(result.stdout.strip())

        if result.stderr:

            log_lines.append("Error:")

            log_lines.append(result.stderr.strip())

    log_lines.append(f"=== Ping結果: {ip} -> {'OK' if success_count == 3 else 'NG'} ===")

    return "OK" if success_count == 3 else "NG"


# ファイル選択ダイアログ

root = tk.Tk()

root.withdraw()

file_path = filedialog.askopenfilename(filetypes=[("CSV files", "*.csv")])


if file_path:

    now_dt = datetime.now()

    log_filename = now_dt.strftime("%Y%m%d-%H%M") + ".log"

    timestamp = now_dt.strftime("%Y/%m/%d %H:%M")


    log_lines = [

        f"Ping 実施日時: {now_dt.strftime('%Y/%m/%d %H:%M:%S')}",

        f"対象CSV: {os.path.basename(file_path)}",

        "-" * 50

    ]


    # CSV読み込み

    with open(file_path, newline="", encoding="utf-8") as f:

        reader = list(csv.reader(f))


    header = reader[0]

    if timestamp in header:

        print(f"{timestamp} の列がすでに存在しています。")

        exit()


    header.append(timestamp)

    updated_rows = [header]


    for row in reader[1:]:

        if len(row) >= 1:

            ip = row[0].strip()

            if ip:

                result = ping(ip, log_lines)

                row += [""] * (len(header) - len(row) - 1)

                row.append(result)

        updated_rows.append(row)


    # CSVバックアップと保存

    backup_path = file_path + ".bak"

    os.rename(file_path, backup_path)

    with open(file_path, "w", newline="", encoding="utf-8") as f:

        writer = csv.writer(f)

        writer.writerows(updated_rows)


    # ログファイル書き出し

    with open(log_filename, "w", encoding="utf-8") as f:

        f.write("\n".join(log_lines))


    print(f"Ping結果を {file_path} に保存しました。")

    print(f"詳細なping出力ログ: {log_filename}(バックアップ: {backup_path})")


else:

    print("ファイルが選択されませんでした。")