我遇到了 USB 端口问题。当我将移动设备连接到 PC USB 端口时,有时会断开连接并立即连接。因此我想持续监控 USB 连接状态。有什么方法可以实时监控连接状态吗?
如果可以仅通过 USB 连接状态获取日志文件就好了
答案1
pyudev
您可以使用监视 USB 连接、将事件记录到文件并将事件打印到控制台的 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)