大量のパソコンの生存確認(マルチスレッド高速版)

Python

大量のパソコンが使われているかを確認することがあります。そこでPythonを使ってIPが通るかで、確認することができます。

import subprocess
import tkinter as tk
from tkinter import messagebox
import concurrent.futures

# 出力ファイル名
output_file_name = "ping_results.txt"

def check_ping(ip):
    """個別のIPアドレスに対してPingを実行し、結果の文字列を返す関数"""
    # WindowsのPingコマンド (-n 1: 1回送信, -w 1000: タイムアウト1000ミリ秒)
    cmd = ["ping", "-n", "1", "-w", "1000", ip]
    result = subprocess.run(cmd, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
    
    if result.returncode == 0:
        return f"{ip} OK"
    else:
        return f"{ip} NG"

def main():
    print("Pingの実行を開始します。高速化のため並列処理を行っています...")

    # 1. チェックする全IPアドレスのリストを先に作成する
    ip_list = []
    # 192.168.0.1 〜 192.168.0.255
    for i in range(1, 256):
        ip_list.append(f"192.168.0.{i}")

    results = []
    
    # 2. ThreadPoolExecutorを使って一斉にPingを打つ (最大50個同時に処理)
    # executor.map を使うことで、処理が終わった順ではなく「元のIPリストの順序」通りに結果を受け取れます
    with concurrent.futures.ThreadPoolExecutor(max_workers=50) as executor:
        for result_text in executor.map(check_ping, ip_list):
            results.append(result_text)

    # 3. 揃った結果をテキストファイルに一気に書き込む
    with open(output_file_name, "w", encoding="utf-8") as f:
        for res in results:
            f.write(res + "\n")

    print(f"Pingの実行が完了しました。結果は {output_file_name} に保存されました。")

    # 4. 完了メッセージボックスの表示
    root = tk.Tk()
    root.withdraw() # 余分な背景ウィンドウを隠す
    messagebox.showinfo("完了", "Pingの実行が完了しました")
    root.destroy()

if __name__ == "__main__":
    main()

Comments

タイトルとURLをコピーしました