本文目录导读:

我来介绍几种通过脚本控制蓝牙开关的方法,适用于不同操作系统:
Windows 系统
PowerShell 脚本
# 启用蓝牙 Start-Service bthserv Get-PnpDevice -Class Bluetooth | Enable-PnpDevice -Confirm:$false # 禁用蓝牙 Stop-Service bthserv Get-PnpDevice -Class Bluetooth | Disable-PnpDevice -Confirm:$false
使用第三方工具
# 使用 DevCon devcon enable "PCI\VEN_8086*" devcon disable "PCI\VEN_8086*"
Linux 系统
使用 bluetoothctl
#!/bin/bash # 开启蓝牙 bluetoothctl power on # 关闭蓝牙 bluetoothctl power off
使用 rfkill
#!/bin/bash # 开启 rfkill unblock bluetooth # 关闭 rfkill block bluetooth
使用 systemd
# 开启 systemctl start bluetooth.service # 关闭 systemctl stop bluetooth.service
macOS 系统
#!/bin/bash # 开启蓝牙 sudo defaults write /Library/Preferences/AppleBluetooth com.apple.Bluetooth.plist ControllerPower -bool true sudo launchctl stop com.apple.bluetoothd sudo launchctl start com.apple.bluetoothd # 关闭蓝牙 sudo defaults write /Library/Preferences/AppleBluetooth com.apple.Bluetooth.plist ControllerPower -bool false sudo launchctl stop com.apple.bluetoothd sudo launchctl start com.apple.bluetoothd
Android 系统
ADB 命令脚本
#!/bin/bash # 开启 adb shell svc bluetooth enable # 关闭 adb shell svc bluetooth disable
Tasker 脚本
<script>
<action>
<name>Bluetooth Off</name>
<code>bluetooth:off</code>
</action>
</script>
Python 脚本(跨平台)
import subprocess
import platform
def control_bluetooth(enable=True):
system = platform.system()
if system == "Windows":
if enable:
subprocess.run('powershell -Command "Start-Service bthserv"', shell=True)
subprocess.run('powershell -Command "Get-PnpDevice -Class Bluetooth | Enable-PnpDevice"', shell=True)
else:
subprocess.run('powershell -Command "Stop-Service bthserv"', shell=True)
subprocess.run('powershell -Command "Get-PnpDevice -Class Bluetooth | Disable-PnpDevice"', shell=True)
elif system == "Linux":
if enable:
subprocess.run(["bluetoothctl", "power", "on"])
else:
subprocess.run(["bluetoothctl", "power", "off"])
elif system == "Darwin": # macOS
# 需要 sudo 权限
cmd = f'sudo defaults write /Library/Preferences/AppleBluetooth com.apple.Bluetooth.plist ControllerPower -bool {"true" if enable else "false"}'
subprocess.run(cmd, shell=True)
# 使用
control_bluetooth(True) # 开蓝牙
control_bluetooth(False) # 关蓝牙
注意事项
- 权限问题:某些操作需要管理员/root权限
- 服务依赖:Windows需要确保相关服务未禁用
- 时间延迟:建议在操作后加入适当延迟,确保生效
- 日志记录:建议记录操作日志便于排查问题
推荐使用场景
- 定时控制:用cron或计划任务定时开关蓝牙
- 自动化脚本:配合其他自动化工具使用
- 远程管理:通过SSH或远程桌面执行脚本
选择最适合你需求的方案即可!