C++环境下的expect远程命令执行
来源:互联网 发布:淘宝哪家螺蛳粉好吃 编辑:程序博客网 时间:2024/04/30 12:36
首先,必须安装几个开发包,在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
- C++环境下的expect远程命令执行
- 使用expect和ssh远程执行命令的脚本
- expect无信任远程批量执行命令
- expect转义符及远程主机执行命令
- Linux下通过EXPECT脚本自动执行ssh远程连接
- Linux下通过EXPECT脚本自动执行ssh远程连接
- Linux 远程执行脚本 expect
- Expect循环登录多台服务器执行命令的脚本
- expect中使用exec执行shell命令的方法
- expect中使用exec执行shell命令的方法
- 使用expect工具ssh登录远程服务器并执行命令操作
- 使用expect telnet 到远程服务器并在服务器上执行一些命令
- salt的远程执行命令
- expect在crontab下执行失败的问题
- 在linux下如何通过expect正确执行自动切换登录,并且执行命令和脚本
- 十七周四次课(11月30日) 20.31 expect脚本同步文件 20.32 expect脚本指定host和要同步的文件 20.33 构建文件分发系统 20.34 批量远程执行命令
- Linux下远程连接windows,执行命令
- linux 下远程执行命令 socket实现
- 怎么说老板才会听?
- 养胃吧
- Sicily 1790. Single Round Match
- 【考试】软件水平考试中的试卷阅评(软考评卷)
- SPDY
- C++环境下的expect远程命令执行
- 西双版纳旅游介绍
- diff和patch给源码做补丁
- 黑马程序员——多线程原来是这么简单
- 风、寒、暑、湿、燥、火
- mmap()介绍
- 新年开始,小计一页
- Sicily 1791. Philia's Problem
- 宏中"#"和"##"的用法