欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

C++环境下的expect远程命令执行

程序员文章站 2022-05-09 12:04:38
...

首先,必须安装几个开发包,在centos/fedora下,可以使用yum安装:

$ yum -y install tcl-devel expect-devel

 

装完以后,就可以使用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;
	}
	//start a connection with remote ssh server
	int fd = exp_spawnl("ssh", "ssh", "-p 22", "username@server_address", "echo start;ls ~;", (char *)0);
	if(fd < 0)
	{
		cout<<"Fail to ssh"<<endl;
		return -1;
	}
	int loop = 1;
	int result;
	while(loop)
	{
		//predefine some expected responses
		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[] = "your_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;
		}
	}
	Tcl_DeleteInterp(tcl);
}

 

 

保存为test-expect.cpp, 编译:

g++ test-expect.cpp -o test-expect -lexpect5.43 -ltcl8.4

 

执行./test-expect,得到远程root用户的根目录列表。 

远程命令的标准输出存在exp_buffer缓冲区。

 

详细的手册可以参考http://www.cims.nyu.edu/cgi-systems/man.cgi?section=3&topic=libexpect