Chinaunix首页 | 论坛 | 博客
  • 博客访问: 8033409
  • 博文数量: 594
  • 博客积分: 13065
  • 博客等级: 上将
  • 技术积分: 10324
  • 用 户 组: 普通用户
  • 注册时间: 2008-03-26 16:44
个人简介

推荐: blog.csdn.net/aquester https://github.com/eyjian https://www.cnblogs.com/aquester http://blog.chinaunix.net/uid/20682147.html

文章分类

全部博文(594)

分类: LINUX

2015-07-30 16:58:34

CLibssh2可以帮助实现相当于Linux的ssh命令的功能。CLibssh2基于libssh2库()实现,不过libssh2的使用较为复杂,而CLibssh2通过封装提供了简单的接口,即可以代码中实现远程执行命令。

头文件:
实现文件:
测试代码:

  1. // 为非线程安全类
  2. //
  3. // 提供执行远程命令的能力,类似于ssh命令
  4. // 可配合utils::CLoginTokener一起使用:#include <mooon/utils/tokener.h>
  5. //
  6. // 使用示例(执行远程命令):
  7. // try
  8. // {
  9. //     int exitcode;
  10. //     std::string exitsignal;
  11. //     std::string errmsg;
  12. //     int num_bytes;
  13. //     net::CLibssh2 libssh2(ip, port, username, password);
  14. //     libssh2.remotely_execute(command, std::cout, &exitcode, &exitsignal, &errmsg, &num_bytes);
  15. // }
  16. // catch (sys::CSyscallException& syscall_ex)
  17. // {
  18. //     fprintf(stderr, "%s\n", syscall_ex.str().c_str());
  19. // }
  20. // catch (utils::CException& ex)
  21. // {
  22. //     fprintf(stderr, "%s\n", ex.str().c_str());
  23. // }
  24. class CLibssh2
  25. {
  26. public:
  27.     // 初始化ssh2环境,为非线程安全函数,每个进程启动时调用一次
  28.     static void init() throw (utils::CException);
  29.     // 清理初始化时产生的资源,每个进程退出时调用一次,或者不再使用ssh2时调用一次
  30.     static void fini();

  31. public:
  32.     // ip 远程主机sshd服务监听的IP地址
  33.     // port 远程主机sshd服务监听的端口号
  34.     // username 用来连接远程主机的用户名
  35.     // password 用户名username的密码
  36.     // timeout_seconds 连接超时时长,单位为秒
  37.     // nonblocking 连接是否主国非阻塞方式,为true表示为非阻塞,为false表示为阻塞方式,建议采用非阻塞方式
  38.     CLibssh2(const std::string& ip, uint16_t port, const std::string& username, const std::string& password, uint32_t timeout_seconds=2, bool nonblocking=true) throw (utils::CException, sys::CSyscallException);
  39.     ~CLibssh2();

  40.     // command 被远程执行的命令,如:whoami
  41.     // out 接收命令输出的流
  42.     // exitcode 远程命令执行结束后的退出代码,如:0
  43.     // exitsignal 远程命令执行时接收到的信号,如:TERM
  44.     // num_bytes 远程命令吐出的字节数
  45.     void remotely_execute(const std::string& command, std::ostream& out, int* exitcode, std::string* exitsignal, std::string* errmsg, int* num_bytes) throw (utils::CException, sys::CSyscallException);

  46.     // 下载远端的文件到本地
  47.     // remote_filepath 被下载的远端文件
  48.     // num_bytes 远端文件的字节数
  49.     void download(const std::string& remote_filepath, std::ostream& out, int* num_bytes) throw (utils::CException, sys::CSyscallException);

  50.     // 上传本地文件到远端
  51.     // num_bytes 本地文件的字节数
  52.     void upload(const std::string& local_filepath, const std::string& remote_filepath, int* num_bytes) throw (utils::CException, sys::CSyscallException);
  53. };



阅读(6149) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~