怎样用脚本批量管理蓝牙配对?

wen 实用脚本 2

本文目录导读:

怎样用脚本批量管理蓝牙配对?

  1. 环境准备与核心工具
  2. Linux 批量配对脚本(使用 bluetoothctl + expect
  3. macOS 批量配对(使用 blueutil
  4. Windows 批量配对(PowerShell + 第三方库)
  5. 批量管理高级技巧
  6. 常见问题与解决
  7. 完整示例仓库推荐

要用脚本批量管理蓝牙配对,通常需要依赖操作系统的蓝牙管理工具(如 Linux 的 bluetoothctlblueutil、Windows 的 BluetoothSetLocalServiceInfo 或 PowerShell 模块),以下是针对常见场景的解决方案。


环境准备与核心工具

Linux(推荐 bluetoothctl + expect / bluetoothctl 非交互模式)

# 安装蓝牙工具
sudo apt install bluez bluez-tools  # Debian/Ubuntu
sudo yum install bluez              # CentOS/RHEL
# 检查蓝牙适配器状态
hciconfig hci0 up

macOS(推荐 blueutil

brew install blueutil

Windows(PowerShell + Get-Bluetooth* Cmdlet)

需要安装 Bluetooth PowerShell 模块(Windows 10/11 自带部分功能,但批量操作受限)。


Linux 批量配对脚本(使用 bluetoothctl + expect

示例:从文件读取 MAC 列表并批量配对

#!/bin/bash
# 配置文件:每行一个 MAC 地址
MAC_LIST="devices.txt"
PAIR_TIMEOUT=15
# 启动蓝牙适配器
echo "power on" | bluetoothctl
sleep 2
# 设置可发现和可配对
echo "discoverable on" | bluetoothctl
echo "pairable on" | bluetoothctl
while read -r mac; do
    echo "处理设备: $mac"
    # 移除已有配对(避免冲突)
    echo "remove $mac" | bluetoothctl
    sleep 2
    # 开始配对(非交互模式可能失败,建议用 expect)
    expect <<EOF
    spawn bluetoothctl
    expect "#"
    send "pair $mac\r"
    expect {
        "Pairing successful" { send_user "配对成功\n"; exit 0 }
        "Failed to pair" { send_user "配对失败: $mac\n"; exit 1 }
        timeout { send_user "超时"; exit 2 }
    }
    send "trust $mac\r"
    send "connect $mac\r"
    expect "#"
EOF
    sleep 3
done < "$MAC_LIST"

更稳健的 bluetoothctl 包装函数

# 使用 Python 调用 bluetoothctl(需要 pexpect)
import pexpect
import sys
def pair_device(mac):
    child = pexpect.spawn('bluetoothctl')
    child.expect('#')
    child.sendline(f'pair {mac}')
    result = child.expect(['Pairing successful', 'Failed to pair', pexpect.TIMEOUT], timeout=15)
    if result == 0:
        child.sendline(f'trust {mac}')
        child.sendline(f'connect {mac}')
        return True
    elif result == 1:
        return False
    else:
        return None

macOS 批量配对(使用 blueutil

#!/bin/bash
# 从文件读取设备 MAC 地址
while read -r mac; do
    echo "配对设备: $mac"
    # 连接(blueutil 会自动尝试配对)
    blueutil --connect "$mac"
    # 检查状态
    if [ $? -eq 0 ]; then
        echo "成功配对并连接 $mac"
    else
        echo "配对失败: $mac"
    fi
    sleep 2
done < devices.txt
# 列出已配对设备
blueutil --paired

Windows 批量配对(PowerShell + 第三方库)

Windows 原生 PowerShell 蓝牙支持有限,需要使用 BluetoothLE 模块或 WinRT API

示例:使用 Get-BluetoothDevice(Windows 10 1809+)

# 导入蓝牙模块(如果可用)
Import-Module "C:\Program Files\WindowsPowerShell\Modules\Bluetooth\1.0.0\Bluetooth.psd1"
$devices = @(
    "AA:BB:CC:DD:EE:FF",
    "11:22:33:44:55:66"
)
foreach ($mac in $devices) {
    $device = Get-BluetoothDevice -MacAddress $mac
    if (-not $device) {
        Write-Host "未找到设备: $mac"
        continue
    }
    # 配对(需要用户交互或提前信任)
    $device.Pair()
    if ($device.PairingStatus -eq "Paired") {
        Write-Host "配对成功: $mac"
    } else {
        Write-Host "配对失败: $mac"
    }
}

使用 bluetoothctl for Windows(通过 WSL 或 Cygwin)

不推荐,因为 Windows 蓝牙栈与 Linux 不兼容。


批量管理高级技巧

1 从 CSV/JSON 文件读取设备信息

# 使用 jq 解析 JSON
cat devices.json | jq -r '.[].mac' | while read mac; do
    echo "配对: $mac"
done

2 自动处理配对请求

蓝牙配对需要用户确认,可以预先设置无确认配对

# Linux 编辑 /etc/bluetooth/main.conf
[Policy]
AutoEnable=true
# 设置 Agent 为 NoInputNoOutput(需重启 bluetooth 服务)

3 错误重试与日志记录

#!/bin/bash
LOGFILE="bluetooth_pair.log"
MAX_RETRIES=3
pair_with_retry() {
    local mac=$1
    local retries=0
    while [ $retries -lt $MAX_RETRIES ]; do
        if bluetoothctl pair "$mac"; then
            echo "$(date) - 成功: $mac" >> "$LOGFILE"
            return 0
        fi
        ((retries++))
        sleep 2
    done
    echo "$(date) - 失败: $mac (重试 $MAX_RETRIES 次)" >> "$LOGFILE"
    return 1
}

常见问题与解决

问题 解决方案
蓝牙未启用 sudo hciconfig hci0 upsudo systemctl start bluetooth
配对需要输入 PIN 使用 bluetoothctl agent NoInputNoOutput 设置无交互模式
设备不在范围内 确保设备可发现,并增加扫描步骤 bluetoothctl scan on
Windows 设备列表为空 以管理员身份运行 PowerShell,并确保蓝牙已开启

完整示例仓库推荐


关键点

  • 批量管理需要非交互工具,Linux 的 bluetoothctl + expect 是最灵活的方案。
  • macOS 用 blueutil 最方便。
  • Windows 蓝牙脚本能力弱,建议用 WSL 或专用硬件。
  • 记得先关闭蓝牙安全策略(如 PIN 码验证),否则批量操作会被卡住。

如果需要针对特定设备(如耳机、传感器)的配对,请提供设备型号,我可以给出更具体的配置。

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