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

来源:互联网 发布:编程中debug是什么意思 编辑:程序博客网 时间:2024/06/07 20:07

 

 

近日需要在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);

}

 

 

 

原创粉丝点击