如何通过Expect脚本提取bluetoothctl属性值并保存到文件
提取Bluetoothctl Notify输出中特定属性值并保存到文件
问题背景
已有Expect脚本可连接指定蓝牙设备(地址34:85:18:6a:52:52),进入GATT菜单选择目标属性并开启notify功能,能成功获取属性值输出,但无法将输出中固定位置的十六进制值(示例中标注的70)保存到.txt文件,尝试script命令未生效。
修改后的Expect脚本
#!/usr/bin/expect -f set prompt "#" set address 34:85:18:6a:52:52 set output_file "acid12.txt" # 初始化输出文件,清空原有内容 set fh [open $output_file w] close $fh spawn bluetoothctl expect -re $prompt send "connect $address\r" expect "Connection successful" sleep 0.2 send "menu gatt\r" sleep 1 send "select-attribute /org/bluez/hci0/dev_34_85_18_6A_52_52/service002e/char0032\r" sleep 2 send "notify on\r" sleep 1 # 循环捕获notify输出并提取目标值 set timeout 10 while {1} { expect { # 正则匹配属性值行,捕获第14个十六进制字段(对应示例中的70) -re {Value:\n ([0-9a-fA-F]+) ([0-9a-fA-F]+) ([0-9a-fA-F]+) ([0-9a-fA-F]+) ([0-9a-fA-F]+) ([0-9a-fA-F]+) ([0-9a-fA-F]+) ([0-9a-fA-F]+) ([0-9a-fA-F]+) ([0-9a-fA-F]+) ([0-9a-fA-F]+) ([0-9a-fA-F]+) ([0-9a-fA-F]+) ([0-9a-fA-F]+)} { set target_value $expect_out(14,string) # 追加写入输出文件 set fh [open $output_file a] puts $fh $target_value close $fh exp_continue } timeout { break } eof { break } } } send "exit\r" sleep 1 send "exit\r" send "quit\r" expect eof
关键修改说明
- 移除无效的
send "script acid12.txt\r"命令:该命令是终端环境下的录屏工具,在Expect脚本中无法正确捕获bluetoothctl的输出流,直接移除。 - 新增文件读写逻辑:通过Expect的文件操作命令
open创建/打开输出文件,用puts将提取到的目标值追加写入,确保每次捕获到数据都能持久化。 - 正则精准匹配目标字段:编写正则表达式匹配属性值的第一行内容,精准捕获第14个十六进制值(对应示例中
70的固定位置)。 - 循环监听输出流:设置10秒超时,持续捕获notify的输出直到超时或进程结束,避免遗漏数据。
使用步骤
- 将修改后的脚本保存为
bt_notify_extract.exp - 赋予执行权限:
chmod +x bt_notify_extract.exp - 运行脚本:
./bt_notify_extract.exp - 脚本结束后,目标值会保存在
acid12.txt文件中,每行对应一次notify输出的目标值。
内容的提问来源于stack exchange,提问作者iUncleMike
相关产品推荐
相关产品推荐

