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)

관련 정보