expect 做 telnet shell 脚本测试

更新日期: 2022-09-15 阅读次数: 2439 字数: 334 分类: Shell

需求背景

用 golang 写了个 tcp 数据上报服务,用来接收硬件设备上的传感器实时数据。 但是测试起来很麻烦,每次增加协议功能,都需要手动重复 telnet 并输入指令,费时费力,且容易忘记指令。

测试技术选型

  • 用 go 写这种自动测试,我能想到的就是新建一个 main package,这样会多出一个目录,感觉麻烦
  • python 涉及到版本依赖,越来越不喜欢
  • 感觉还是直接用 shell 写更简单方便,且直观

expect

还是用 expect 更合理一些,因为要判断 tcp 的返回数据格式,是否跟协议规定的一致。

Expect is a program that "talks" to other interactive programs according to a script. Following the script, Expect knows what can be expected from a program and what the correct response should be.

Ubuntu 上安装 expect

sudo apt install expect

测试脚本

#!/usr/bin/expect

# If it all goes pear shaped the script will timeout after 20 seconds.
set timeout 20

# This spawns the telnet program and connects it
spawn telnet 127.0.0.1 9999
sleep 3

send "name: 123456"
send "\r"
expect "name_ok"
sleep 1

# 心跳包
send "hb"
send "\r"
expect "hb_ok"
sleep 1

# 传感器数据
send "data: 1,2,3,4,5,6,7,8,9"
send "\r"
expect "data_ok"
sleep 1

# This hands control of the keyboard over to you (Nice expect feature!)
interact

执行

chmod +x test.expect
./test.expect

参考

https://stackoverflow.com/questions/7013137/automating-telnet-session-using-bash-scripts

微信关注我哦 👍

大象工具微信公众号

我是来自山东烟台的一名开发者,有感兴趣的话题,或者软件开发需求,欢迎加微信 zhongwei 聊聊, 查看更多联系方式