expect 极简示例,用脚本自动填写要输入的内容

极简示例、清爽易懂易修改

【以下是 my.sh 内容,读取用户输入并回显的普通 shell 脚本】
#!/bin/sh
read -p "Input 1: " input
echo "My Input 1 is: $input"
read -p "Input 2: " input
echo "My Input 2 is: $input"

【运行一下看看】
[root@a ~]# sh my.sh
Input 1: abc # 手动输入 abc
My Input 1 is: abc
Input 2: # 手动输入 回车键
My Input 2 is: 

【以下是 test.sh 内容,调用 my.sh 脚本,并根据提示自动输入对应内容】
#!/usr/bin/expect
set X www
set timeout 1
spawn ./my.sh
expect "Inputi 1: "
send "abc\r"
expect "Input 2: "
send "\r"
expect eof
exit

【运行一下看看】
[root@a ~]# chmod +x test.sh # 先加运行权限
[root@a ~]# ./test.sh 
spawn ./my.sh
Input 1: abc
My Input 1 is: abc
Input 2: 
My Input 2 is: 
嗯嗯,完全一样

【如果你有变量要操作,可以这样设置】
#!/usr/bin/expect
set X www
set timeout 1
spawn ./my.sh
expect "Inputi 1: "
send "abc\r"
expect "Input 2: "
send "$X\r"
expect eof
exit

【运行结果】
[root@a ~]# ./test.sh 
spawn ./my.sh
Input 1: abc
My Input 1 is: abc
Input 2: www
My Input 2 is: www

猜你喜欢

转载自blog.csdn.net/PanDD_0_1/article/details/79309047