linux expect 的基本使用方法

2023-04-11 06:00:00 linux expect 使用方法
expect 是一个用来控制命令行操作的工具,主要用来模拟类似于人类的交互操作。 expect 的语法和 Tcl 语言类似,因此使用起来也相对容易。 expect 的基本使用方法如下: 1. 首先需要安装 expect,在 Ubuntu 系统中可以使用如下命令进行安装: sudo apt-get install expect 2. 编写 expect 脚本,脚本的内容格式如下: #!/usr/bin/expect -f set timeout 30 spawn expect "string1" send "string2\r" expect "string3" send "string4\r" ... expect eof 其中, 和 是需要执行的命令和参数,"string1"、"string2"、"string3"、"string4" 等字符串是交互操作过程中的提示符和输入内容。 3. 使用如下命令执行 expect 脚本: expect 其中, 是脚本文件的名称。 示例 假设我们要执行的命令是 ls,命令的执行过程如下图所示: 要使用 expect 进行模拟,需要编写如下脚本: #!/usr/bin/expect -f set timeout 30 spawn ls expect eof 执行脚本之后,可以看到类似如下的输出: [email protected]:~/expect$ ./test.exp spawn ls test.exp [email protected]:~/expect$ 可以看到,expect 脚本执行完成之后,会直接返回命令行,并没有执行命令的输出。这是因为我们的脚本中没有指定任何交互操作。 要想让 expect 脚本执行命令的输出,需要在脚本中指定相应的交互操作。例如,我们可以在脚本中加入如下内容: expect "total 4" send "ls -l\r" 执行脚本之后,可以看到类似如下的输出: [email protected]:~/expect$ ./test.exp spawn ls test.exp total 4 -rw-rw-r-- 1 ouyang ouyang 0 Apr 27 21:25 test.exp [email protected]:~/expect$ 可以看到,expect 脚本执行完成之后,会继续执行 ls -l 命令的输出。 除了指定交互操作之外,还可以使用 expect_before 和 expect_after 命令来指定执行命令之前和之后需要执行的操作。例如,我们可以在脚本中加入如下内容: expect_before eof { send "exit\r" } 执行脚本之后,可以看到类似如下的输出: [email protected]:~/expect$ ./test.exp spawn ls test.exp total 4 -rw-rw-r-- 1 ouyang ouyang 0 Apr 27 21:25 test.exp [email protected]:~/expect$ 可以看到,expect 脚本执行完成之后,会自动执行 exit 命令来退出当前终端。 expect 脚本还可以通过参数来控制命令的执行。例如,我们可以使用如下命令来执行脚本: expect ./test.exp arg1 arg2 在脚本中,可以使用 $argv 变量来引用参数,例如: set arg1 [lindex $argv 0] set arg2 [lindex $argv 1] 执行脚本之后,可以看到类似如下的输出: [email protected]:~/expect$ ./test.exp a b spawn ls test.exp a b [email protected]:~/expect$ 可以看到,expect 脚本执行完成之后,会将参数 a 和 b 作为命令的输入来执行 ls 命令。 总结 以上就是 expect 的基本使用方法。expect 的功能非常强大,除了可以用来模拟人类的交互操作之外,还可以用来实现自动化部署、自动化测试等。因此,使用 expect 可以大大提高工作效率。

相关文章