1.ubuntu12.04 32位
IDE:Clion
安装 sudo apt-get install tcl-devel expect-devel
----------------------------------------------------
2.main.cpp
-----------------------------------------------------
#include <tcl.h>
#include <expect.h>
#include <stdio.h>
#include <unistd.h>
#include <iostream>
#include <expect_tcl.h>
using namespace std;
int main(){
// extern int exp_timeout;
// exp_timeout = 1;
Tcl_Interp *tcl;
tcl = Tcl_CreateInterp();
if (Expect_Init(tcl) != TCL_OK){
puts("failure");
return 1;
}
int fd = exp_spawnl("sudo","sudo","su",(char *)0);
if(fd < 0){
cout<<"Fail"<<endl;
return -1;
}
int loop = 1;
int result;
char pas[] = "123\n";
char cmd1[]="ls -lh\n";
char cmd2[]="echo 好朋友\n";
char cmd3[]="echo 我的好朋友\n";
int flag=0;
while(loop){
result = exp_expectl(fd, exp_regexp, ".*assword.*", 1, exp_exact,"ℛ",2,exp_end);
// result = exp_expectl(fd, exp_regexp, ".*assword.*", 1,exp_end);
switch(result){
case 1:
write(fd, pas, sizeof(pas) - 1);
break;
case 2:
if(flag==0){
write(fd, cmd1,sizeof(cmd1) - 1);
write(fd, cmd2,sizeof(cmd2) - 1);
flag=1;
break;
}else if(flag==1){
write(fd, cmd3,sizeof(cmd3) - 1);
flag=2;
break;
}else{
break;
}
case EXP_EOF:
cout << "\nEOF";
loop = 0;
break;
case EXP_TIMEOUT:
cout<<"\nTime out";
loop = 0;
break;
}
}
Tcl_DeleteInterp(tcl);
return 0;
}
---------------------------------------------------
3.CMakeLists.txt
--------------------------------------------------
cmake_minimum_required(VERSION 3.13)
project(expTcl)
set(CMAKE_CXX_STANDARD 14)
link_directories(/usr/local/lib /usr/local/lib/expect5.45)
add_executable(expTcl main.cpp)
target_link_libraries(expTcl tcl8.4 expect5.45)