sftp通信攻关——qt环境下使用c++实现

  最近涉及到sftp通信编码。上传测试代码记录一下。

  头文件:

#ifndef SFTPMANAGER_H
#define SFTPMANAGER_H

#ifdef WIN32
#include "libssh2/win32/libssh2_config.h"
#endif
#include 
#include 
#include 
#include 
#include 
#include 
#ifdef WIN32
#include 
#include 
#pragma comment(lib, "Ws2_32.lib")
#else
#include 
#include 
#include 
#endif



class SftpManager
{
public:

    SftpManager();
    virtual ~SftpManager();

    bool connect(std::string szIp, int nPort = 22);

    bool createSession();

    bool login(std::string szUserName, std::string szPassword);

    bool read();

    bool mkdir();

    bool readAndWrite();

private:
    SOCKET m_socket;
    LIBSSH2_SESSION *m_session = nullptr;

    std::vector m_channels;
    //std::vector m_channel_mutexs;
    std::vector> m_channel_mutexs;
    static std::string m_ipAddress;
    static int m_port;
    static std::string m_username;
    static std::string m_password;

    static void initConnectionInfo();
    static int waitsocket(int socket_fd, LIBSSH2_SESSION *session);
     void shutDown();
    static std::string ipAddress();
    static std::string username();
    static std::string password();
    static int port();
};

#endif // SFTPMANAGER_H

源文件:

#include "SftpManager.h"
#include 
#include 
#define STORAGE "d:\\src\\test.txt"

std::string SftpManager::m_password;
std::string SftpManager::m_username;
std::string SftpManager::m_ipAddress;
int SftpManager::m_port;
const char *sftppath = "/home/loohos-01/abc/test";
const char *m_sftppath = "/home/loohos-01/abc/test_mkdir";
const char *m_dest = "/home/loohos-01/abc/test_dest";




SftpManager::SftpManager()
{

}
SftpManager::~SftpManager()
{
    if (!m_channels.empty()){
        for (auto channel : m_channels) if (nullptr != channel) libssh2_channel_free(channel);
        m_channels.clear();
    }
    /*
    if (!m_channel_mutexs.empty()){
        for (auto mtx : m_channel_mutexs) delete mtx;
        m_channel_mutexs.clear();
    }
    */

    if (nullptr != m_session){
        libssh2_session_disconnect(m_session, "Bye bye, Thank you");
        libssh2_session_free(m_session);
        m_session = nullptr;
    }

    libssh2_exit();

    if (INVALID_SOCKET != m_socket) closesocket(m_socket);

#ifdef WIN32
        WSACleanup();
#endif

}

int SftpManager::waitsocket(int socket_fd, LIBSSH2_SESSION *session )
{
    struct timeval timeout;
    int rc;
    fd_set fd;
    fd_set *writefd = NULL;
    fd_set *readfd = NULL;
    int dir;

    timeout.tv_sec = 10;
    timeout.tv_usec = 0;

    FD_ZERO(&fd);
    FD_SET(socket_fd, &fd);

    dir = libssh2_session_block_directions(session);

    if(dir & LIBSSH2_SESSION_BLOCK_INBOUND)
        readfd = &fd;

    if(dir & LIBSSH2_SESSION_BLOCK_OUTBOUND)
        writefd = &fd;

    rc = select(socket_fd + 1, readfd, writefd, NULL, &timeout);

    return rc;
}

bool SftpManager::connect(std::string szIp, int nPort)
{
    unsigned long hostaddr;
    int sock, i,

你可能感兴趣的:(c++,QT,通信,sftp,ssh2,qt,c++)