本文目录导读:

Windows (PowerShell)
# 方法1:使用 Get-PnpDevice
Get-PnpDevice -Class Bluetooth | Where-Object {$_.Status -eq "OK"} |
Select-Object FriendlyName, DeviceID, Status
# 方法2:查看所有蓝牙设备(包括已配对和连接的)
Get-PnpDevice -Class Bluetooth |
Where-Object {$_.InstanceId -like "*DEVICE*"} |
Select-Object FriendlyName, DeviceID, Status
Windows (CMD/Batch)
@echo off
REM 使用 wmic 命令
wmic path Win32_PnPEntity where "ClassGuid='{e0cbf06c-cd8b-4647-bb8a-263b43f0f974}'" get Name,DeviceID,Status
Linux (Bash)
#!/bin/bash
# 方法1:使用 bluetoothctl
echo "已连接的蓝牙设备:"
bluetoothctl devices Connected | cut -d' ' -f3-
# 方法2:使用 hcitool (需要 bluez 工具)
if command -v hcitool &> /dev/null; then
echo -e "\n通过 hcitool 扫描:"
hcitool con
fi
# 方法3:通过 dbus 获取
echo -e "\n通过 D-Bus 获取:"
dbus-send --system --dest=org.bluez --print-reply \
/org/bluez/hci0 org.freedesktop.DBus.ObjectManager.GetManagedObjects
macOS (Bash)
#!/bin/bash
# 使用 system_profiler
echo "已连接的蓝牙设备:"
system_profiler SPBluetoothDataType | grep "Connected:" -A 5 |
grep -E "^\s+[A-Za-z]" | sed 's/^[[:space:]]*//'
# 或使用蓝牙命令行工具
/usr/sbin/blued -s 2>/dev/null | grep "Connected"
跨平台 Python 脚本
import subprocess
import platform
import sys
def get_connected_bluetooth():
system = platform.system().lower()
if system == "windows":
return get_windows_bluetooth()
elif system == "linux":
return get_linux_bluetooth()
elif system == "darwin": # macOS
return get_macos_bluetooth()
else:
print(f"不支持的操作系统: {system}")
return []
def get_windows_bluetooth():
try:
# 使用 PowerShell
cmd = 'powershell "Get-PnpDevice -Class Bluetooth | Where-Object {$_.Status -eq \'OK\'} | Select-Object FriendlyName"'
result = subprocess.run(cmd, capture_output=True, text=True, shell=True)
devices = result.stdout.strip().split('\n')[3:] # 跳过前3行
return [d.strip() for d in devices if d.strip()]
except Exception as e:
print(f"错误: {e}")
return []
def get_linux_bluetooth():
try:
result = subprocess.run(
['bluetoothctl', 'devices', 'Connected'],
capture_output=True, text=True
)
devices = []
for line in result.stdout.strip().split('\n'):
if line.startswith('Device'):
# 格式: Device MAC_ADDRESS Device_Name
parts = line.split()
if len(parts) >= 3:
devices.append(' '.join(parts[2:]))
return devices
except Exception as e:
print(f"错误: {e}")
return []
def get_macos_bluetooth():
try:
result = subprocess.run(
['system_profiler', 'SPBluetoothDataType'],
capture_output=True, text=True
)
output = result.stdout
devices = []
lines = output.split('\n')
is_connected = False
for i, line in enumerate(lines):
if 'Connected:' in line:
is_connected = True
continue
if is_connected and line.strip() and not line.startswith(' '):
is_connected = False
if is_connected and line.strip() and ':' not in line:
devices.append(line.strip())
return devices
except Exception as e:
print(f"错误: {e}")
return []
# 使用示例
if __name__ == "__main__":
connected_devices = get_connected_bluetooth()
if connected_devices:
print("已连接的蓝牙设备:")
for i, device in enumerate(connected_devices, 1):
print(f"{i}. {device}")
else:
print("未找到已连接的蓝牙设备")
Node.js (需要管理员权限)
const { exec } = require('child_process');
const os = require('os');
function getConnectedBluetooth() {
return new Promise((resolve, reject) => {
let cmd;
const platform = os.platform();
if (platform === 'win32') {
cmd = 'powershell "Get-PnpDevice -Class Bluetooth | Where-Object {$_.Status -eq \'OK\'} | Select-Object FriendlyName"';
} else if (platform === 'linux') {
cmd = 'bluetoothctl devices Connected';
} else if (platform === 'darwin') {
cmd = 'system_profiler SPBluetoothDataType | grep "Connected:" -A 5';
} else {
reject(new Error(`不支持的操作系统: ${platform}`));
return;
}
exec(cmd, { encoding: 'utf8' }, (error, stdout, stderr) => {
if (error) {
reject(error);
return;
}
resolve(stdout.trim());
});
});
}
// 使用示例
getConnectedBluetooth()
.then(devices => {
console.log('已连接的蓝牙设备:\n', devices);
})
.catch(error => {
console.error('错误:', error.message);
});
注意事项
- Windows:某些命令需要管理员权限
- Linux:需要安装
bluez工具包 - macOS:需要启用蓝牙权限
- 跨平台:建议使用 Python 脚本,因为它更容易处理不同操作系统
选择最适合你操作系统和需求的脚本即可。