您的位置:首页 > 编程语言 > C语言/C++

C++中expect的使用(ssh 和 scp)

2011-03-31 14:20 435 查看
近日需要在c++中使用expect, 找了好久的资料才完成。。。贴代码

#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 = 100;

Tcl_Interp *tcl;

tcl = Tcl_CreateInterp();

if (Expect_Init(tcl) != TCL_OK)

{

puts("failure");

return 1;

}

int fd = exp_spawnl("ssh","ssh","account@machine", "echo start;ls ~;",(char *)0);

if(fd <0)

{

cout<<"Fail to ssh"<<endl;

return -1;

}

int loop =1;

int result;

while(loop)

{

result = exp_expectl(fd,exp_glob,"*assword: ",1,

exp_exact, "Permission denied, please try again.", 2,

exp_regexp, "(The authenticity of host)(.)*(Are you sure you want to continue connecting (yes/ no)?)", 3,

exp_end);

char pas[] = "password/n";

switch(result)

{

case 1:

write(fd,pas,sizeof(pas)-1);

break;

case 2:

cout <<"wrong password"<<endl;

break;

case 3:

cout<<"connect security"<<endl;

write(fd,"yes/n",4);

break;

case EXP_EOF:

cout <<"EOF/n";

loop=0;

break;

case EXP_TIMEOUT:

cout<<"Time out/n";

loop=0;

break;

default:

cout<<"logged in "<<result<<endl;

loop=0;

break;

}

}

fd = exp_spawnl("scp","scp","-r","/home/work/ci/shell", "account@machine:/home/work/ci",(char *)0);

if(fd <0)

{

cout<<"Fail to scp"<<endl;

}

else

{

int loop =1;

int result;

while(loop)

{

result = exp_expectl(fd,exp_glob,"*assword: ",1,

exp_exact, "Permission denied, please try again.", 2,

exp_regexp, "(The authenticity of host)(.)*(Are you sure you want to continue connecting (yes/ no)?)", 3,

exp_end);

char pas[]="password/n";

switch(result)

{

case 1:

write(fd,pas,sizeof(pas)-1);

break;

case 2:

cout <<"wrong password"<<endl;

loop=0;

break;

case 3:

cout<<"connect security"<<endl;

write(fd,"yes/n",4);

break;

case EXP_EOF:

cout <<"EOF/n";

loop=0;

break;

case EXP_TIMEOUT:

cout<<"Time out/n";

loop=0;

break;

default:

cout<<"logged in "<<result<<endl;

loop=0;

break;

}

}

}

Tcl_DeleteInterp(tcl);

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: