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
头文件: 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);
- };