本文目录导读:

- Windows - PowerShell脚本
- Windows - C# (使用WMI)
- Linux - udev规则 + 脚本
- Linux - Python (使用pyudev)
- macOS - IOKit框架 (C语言)
- 跨平台 - Python (使用watchdog)
- Windows - 使用Win32 API (C++)
- 选择建议
Windows - PowerShell脚本
# 使用WMI事件监控
$query = "SELECT * FROM Win32_DeviceChangeEvent WHERE EventType = 2"
Register-WmiEvent -Query $query -Action {
Write-Host "USB设备已插入"
# 获取新设备信息
Get-WmiObject Win32_USBControllerDevice | Select-Object Dependent
}
Windows - C# (使用WMI)
using System.Management;
// 创建WMI事件监控
WqlEventQuery query = new WqlEventQuery(
"SELECT * FROM Win32_DeviceChangeEvent WHERE EventType = 2");
ManagementEventWatcher watcher = new ManagementEventWatcher(query);
watcher.EventArrived += new EventArrivedEventHandler(DeviceInserted);
watcher.Start();
void DeviceInserted(object sender, EventArrivedEventArgs e) {
Console.WriteLine("USB设备已插入");
// 获取设备详细信息
foreach (ManagementBaseObject device in new ManagementObjectSearcher(
"SELECT * FROM Win32_PnPEntity WHERE ConfigManagerErrorCode = 0").Get()) {
Console.WriteLine(device["Description"]);
}
}
Linux - udev规则 + 脚本
# 创建udev规则文件 /etc/udev/rules.d/99-usb-monitor.rules ACTION=="add", SUBSYSTEM=="usb", RUN+="/usr/local/bin/usb-inserted.sh"
# usb-inserted.sh脚本内容 #!/bin/bash echo "$(date) - USB设备已插入" >> /var/log/usb.log # 获取设备信息 echo "设备ID: $ID_MODEL_ID" >> /var/log/usb.log echo "制造商: $ID_VENDOR" >> /var/log/usb.log
Linux - Python (使用pyudev)
import pyudev
context = pyudev.Context()
monitor = pyudev.Monitor.from_netlink(context)
monitor.filter_by(subsystem='usb')
for device in iter(monitor.poll, None):
if device.action == 'add':
print(f"USB设备插入: {device.device_node}")
print(f"制造商: {device.get('ID_VENDOR')}")
print(f"产品: {device.get('ID_MODEL')}")
macOS - IOKit框架 (C语言)
#include <IOKit/IOKitLib.h>
#include <IOKit/usb/IOUSBLib.h>
void deviceAdded(void *refCon, io_iterator_t iterator) {
io_service_t service;
while ((service = IOIteratorNext(iterator))) {
printf("USB设备已插入\n");
IOObjectRelease(service);
}
}
int main() {
IONotificationPortRef notifyPort = IONotificationPortCreate(kIOMasterPortDefault);
CFRunLoopSourceRef runLoopSource = IONotificationPortGetRunLoopSource(notifyPort);
CFRunLoopAddSource(CFRunLoopGetCurrent(), runLoopSource, kCFRunLoopDefaultMode);
io_iterator_t iterator;
IOServiceAddMatchingNotification(notifyPort,
kIOFirstMatchNotification,
IOServiceMatching(kIOUSBDeviceClassName),
deviceAdded, NULL, &iterator);
CFRunLoopRun();
return 0;
}
跨平台 - Python (使用watchdog)
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler
import time
class USBHandler(FileSystemEventHandler):
def on_created(self, event):
if '/media/' in event.src_path or '/mnt/' in event.src_path:
print(f"USB设备挂载点创建: {event.src_path}")
observer = Observer()
observer.schedule(USBHandler(), path='/media/', recursive=True)
observer.start()
try:
while True:
time.sleep(1)
except KeyboardInterrupt:
observer.stop()
observer.join()
Windows - 使用Win32 API (C++)
#include <windows.h>
#include <dbt.h>
#include <iostream>
LRESULT CALLBACK WindowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam) {
switch (uMsg) {
case WM_DEVICECHANGE:
if (wParam == DBT_DEVICEARRIVAL) {
PDEV_BROADCAST_HDR lpdb = (PDEV_BROADCAST_HDR)lParam;
if (lpdb->dbch_devicetype == DBT_DEVTYP_DEVICEINTERFACE) {
std::cout << "USB设备已插入" << std::endl;
}
}
break;
}
return DefWindowProc(hwnd, uMsg, wParam, lParam);
}
选择建议
| 平台 | 推荐方法 | 复杂度 |
|---|---|---|
| Windows | PowerShell / WMI | 低 |
| Linux | udev规则 + shell脚本 | 低 |
| macOS | IOKit框架 | 中 |
| 跨平台 | Python + pyudev/watchdog | 中 |
选择方法时考虑的因素:
- 是否需要实时响应
- 需要获取哪些设备信息(ID、制造商等)
- 是否需要兼容多个操作系统
- 开发语言偏好