前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >远程执行命令的C++实现CLibssh2

远程执行命令的C++实现CLibssh2

作者头像
一见
发布2018-08-10 15:37:35
2K0
发布2018-08-10 15:37:35
举报
文章被收录于专栏:蓝天蓝天蓝天

CLibssh2可以帮助实现相当于Linux的ssh命令的功能。CLibssh2基于libssh2库(http://www.libssh2.org)实现,不过libssh2的使用较为复杂,而CLibssh2通过封装提供了简单的接口,即可以代码中实现远程执行命令。 头文件:https://github.com/eyjian/mooon/blob/master/common_library/include/mooon/net/libssh2.h 实现文件:https://github.com/eyjian/mooon/blob/master/common_library/src/net/libssh2.cpp 测试代码:https://github.com/eyjian/mooon/blob/master/common_library/test/net/ut_libssh2.cpp

 // 为非线程安全类
  
 //
 
 // 提供执行远程命令的能力,类似于ssh命令
 
 // 可配合utils::CLoginTokener一起使用:#include <mooon/utils/tokener.h>
 
 //
 
 // 使用示例(执行远程命令):
 
 // try
 
 // {
 
 // int exitcode;
 
 //  std::string exitsignal;
 
 //  std::string errmsg;
 
 //  int num_bytes;
 
 //  net::CLibssh2 libssh2(ip, port, username, password);
 
 //  libssh2.remotely_execute(command, std::cout, &exitcode, &exitsignal, &errmsg, &num_bytes);
 
 // }
 
 // catch (sys::CSyscallException& syscall_ex)
 
 // {
 
 //  fprintf(stderr, "%s\n", syscall_ex.str().c_str());
 
 // }
 
 // catch (utils::CException& ex)
 
 // {
 
 //  fprintf(stderr, "%s\n", ex.str().c_str());
 
 // }
 
 class CLibssh2
 
 {
 
 public:
 
 // 初始化ssh2环境,为非线程安全函数,每个进程启动时调用一次
 
 			    static void init() throw (utils::CException);
 
 // 清理初始化时产生的资源,每个进程退出时调用一次,或者不再使用ssh2时调用一次
 
 			    static void fini();
 
 
 
 public:
 
 // ip 远程主机sshd服务监听的IP地址
 
 // port 远程主机sshd服务监听的端口号
 
 // username 用来连接远程主机的用户名
 
 // password 用户名username的密码
 
 // timeout_seconds 连接超时时长,单位为秒
 
 // nonblocking 连接是否主国非阻塞方式,为true表示为非阻塞,为false表示为阻塞方式,建议采用非阻塞方式
 
 			    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);
 
 ~CLibssh2();
 
 
 
 // command 被远程执行的命令,如:whoami
 
 // out 接收命令输出的流
 
 // exitcode 远程命令执行结束后的退出代码,如:0
 
 // exitsignal 远程命令执行时接收到的信号,如:TERM
 
 // num_bytes 远程命令吐出的字节数
 
 			    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);
 
 
 
 // 下载远端的文件到本地
 
 // remote_filepath 被下载的远端文件
 
 // num_bytes 远端文件的字节数
 
 			    void download(const std::string& remote_filepath, std::ostream& out, int* num_bytes) throw (utils::CException, sys::CSyscallException);
 
 
 
 // 上传本地文件到远端
 
 // num_bytes 本地文件的字节数
 
 			    void upload(const std::string& local_filepath, const std::string& remote_filepath, int* num_bytes) throw (utils::CException, sys::CSyscallException);
 
 }; 
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2015-07-30 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档