怎么用脚本获取蓝牙设备

wen 实用脚本 3

本文目录导读:

怎么用脚本获取蓝牙设备

  1. Python (跨平台方案)
  2. Shell 脚本
  3. Node.js
  4. 平台特定方案
  5. 安装依赖
  6. 注意事项

Python (跨平台方案)

使用 pybluez 库(推荐)

import bluetooth
# 扫描附近的蓝牙设备
print("正在扫描蓝牙设备...")
devices = bluetooth.discover_devices(duration=8, lookup_names=True, flush_cache=True)
for addr, name in devices:
    print(f"设备名称: {name}")
    print(f"设备地址: {addr}")
    print("---")

使用 bleak 库(适用于BLE设备)

import asyncio
from bleak import BleakScanner
async def scan_devices():
    devices = await BleakScanner.discover()
    for device in devices:
        print(f"名称: {device.name}")
        print(f"地址: {device.address}")
        print(f"RSSI: {device.rssi}")
        print("---")
asyncio.run(scan_devices())

Shell 脚本

macOS

#!/bin/bash
# 扫描蓝牙设备
system_profiler SPBluetoothDataType | grep -A 5 "Address:"
# 或使用 blueutil
brew install blueutil
blueutil --paired
blueutil --inquiry 4

Linux

#!/bin/bash
# 需要安装 bluez
sudo apt install bluez  # Debian/Ubuntu
# 扫描设备
hcitool scan
# 或使用 bluetoothctl
bluetoothctl scan on
sleep 5
bluetoothctl devices

Windows (PowerShell)

# 获取蓝牙设备
Get-PnpDevice -Class Bluetooth | Select-Object FriendlyName, Status
# 使用蓝牙API(需要管理员权限)
Add-Type -AssemblyName System.Runtime.WindowsRuntime
$asyncOperation = [Windows.Devices.Bluetooth.BluetoothDevice]::FindAllAsync()
$result = $asyncOperation.GetAwaiter().GetResult()
foreach ($device in $result) {
    Write-Host "设备: $($device.Name) - $($device.DeviceId)"
}

Node.js

const noble = require('@abandonware/noble');
noble.on('stateChange', async (state) => {
    if (state === 'poweredOn') {
        console.log('开始扫描...');
        await noble.startScanningAsync([], false);
    }
});
noble.on('discover', (peripheral) => {
    console.log(`设备名称: ${peripheral.advertisement.localName}`);
    console.log(`设备地址: ${peripheral.address}`);
    console.log(`RSSI: ${peripheral.rssi}`);
    console.log('---');
});
setTimeout(() => {
    noble.stopScanningAsync();
    console.log('扫描完成');
    process.exit(0);
}, 10000);

平台特定方案

Android (Termux)

# 需要安装 Termux:API
pkg install termux-api
termux-bluetooth-scan

iOS (Shortcuts)

可以使用快捷指令App中的"获取蓝牙设备"动作

安装依赖

Python:

pip install pybluez bleak

Node.js:

npm install @abandonware/noble

注意事项

  1. 权限问题:大多数系统需要管理员/root权限
  2. 蓝牙适配器:确保系统蓝牙已开启
  3. 兼容性:不同操作系统/蓝牙版本可能有差异
  4. 隐私限制:iOS系统对蓝牙扫描有严格限制

选择哪种方案取决于你的操作系统和具体需求,Python的pybluez是最通用的选择,而bleak更适合现代BLE设备。

抱歉,评论功能暂时关闭!