我正面临一个usb接口的问题。当我将移动设备连接到我的PC USB端口时,有时它会断开并立即连接。所以我想要连续监控USB连接状态。有什么方法可以监视连接状态吗?
如果能够获得日志文件,并且只有usb连接状态,那就更好了。
发布于 2023-03-30 05:36:38
您可以使用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)
https://askubuntu.com/questions/1461546
复制相似问题