USB接続ステータスを継続的に監視

USB接続ステータスを継続的に監視

USB ポートに問題があります。モバイル デバイスを PC の USB ポートに接続すると、切断されたり、すぐに接続されたりすることがよくあります。そのため、USB 接続ステータスを継続的に監視したいと考えています。接続ステータスをリアルタイムで監視する方法はありますか?

USB接続ステータスだけでもログファイルを取得できれば良いでしょう

答え1

pyudevUSB 接続を監視し、イベントをファイルに記録し、イベントをコンソールに出力する Python スクリプトを使用してこれを実行できます。

パッケージをインストールすることから始めましょうpip install pyudev

スクリプトは次のとおりです。

import os
import sys
import pyudev

from datetime import datetime

def log_event(event_type, device):
    timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    message = f"{timestamp} - {event_type}: {device.get('ID_SERIAL_SHORT') or device.get('ID_SERIAL')} - {device.get('ID_MODEL')}"

    with open("usb_connection_log.txt", "a") as log_file:
        log_file.write(message + "\n")

    print(message)

def monitor_usb_events():
    context = pyudev.Context()
    monitor = pyudev.Monitor.from_netlink(context)
    monitor.filter_by(subsystem='usb')

    for action, device in monitor:
        if action == 'add' and 'ID_SERIAL' in device:
            log_event("Connected", device)
        elif action == 'remove' and 'ID_SERIAL' in device:
            log_event("Disconnected", device)

if __name__ == "__main__":
    try:
        monitor_usb_events()
    except KeyboardInterrupt:
        print("\nMonitoring stopped.")
        sys.exit(0)

関連情報