expect的if分支问题
为什么expect中send的数据还留在缓存呢??
cp.sh的expect脚本如下:
- C/C++ code
#!/usr/local/bin/expect # 解释器声明set timeout -1# 设置超时时间,单位秒 #scp拷贝指令spawn .1expect {"*num*" { send "34\r"; exp_continue}"yes/no" { send "yes\r"; exp_continue}"*password*" {send "123456\r"}}expect eof# 模拟结束,把控制权交还控制台,如果不加这个,就等于直接退出了#interact
1.c的源文件如下:
- C/C++ code
#include <stdio.h>int main(){ int a = 0; char password[20] = {0}; printf("please input a num:"); scanf("%d", &a); printf("this num is %d !\n", a); fflush(stdout); printf("please input a password:"); scanf("%s", password); printf("this password is %s !\n", password); return 0;}
运行的结果是:
- C/C++ code
root@192.168.200.207[root@localhost 1020]# ./cp.shspawn ./1please input a num:34this num is 34 !please input a password:34this password is 34 !123456root@192.168.200.207[root@localhost 1020]#
[解决办法]
please input a num:34
this num is 34 !
please input a password:34
this password is 34 !
123456
这部分内容的问题,分析一下代码:
int main()
{
int a = 0;
char password[20] = {0};
printf("please input a num:");
scanf("%d", &a);
printf("this num is %d !\n", a);
fflush(stdout);
printf("please input a password:");
scanf("%s", password);
printf("this password is %s !\n", password);
return 0;
}
当执行到printf("please input a num:");时候,会匹配到num这一行,这时expect会返回一个数字,然后再执行printf("this num is %d !\n", a); 这个时候会再一次的匹配上num那一行,同理password也是一样的。