我遇到了 USB 連接埠問題。當我將行動裝置連接到 PC USB 連接埠時,有時會斷開連接並立即連接。所以我想持續監控USB連線狀態。有什麼方法可以即時監控連線狀態嗎?
如果能取得只有 USB 連線狀態的日誌檔就好了
答案1
您可以使用pyudev
python 腳本來監視 USB 連接、將事件記錄到檔案並將事件列印到控制台。
首先安裝包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)