利用第三方库实现sftp上传文件

封装一个类CSftp

upload_sftp.h

#define UPLOAD_SFTP_H
#include
#include

#include "libssh2_sftp.h"

class CSftp
{
public:
    CSftp();
    ~CSftp();
    bool Init(QString remotePath ,QString ip = "10.11.22.34", int port = 22, QString user = "test", QString pwd = "test");
    bool Fini();
    bool CreateFile(const std::string fullPathFileName);
    bool CreateDir(const std::string fullPathName);
    bool UploadSftp(const char * data, const int size,const std::string fullPathName,const std::string fileName);
private:
    bool ConnectToHost();
    bool DisConnHost();
 private:
    int     m_nPort;
    int     m_sock;
    QString m_strIP;
    QString m_strUser;
    QString m_strPwd;
    QString m_remotePath;
    LIBSSH2_SESSION   *m_session;
    LIBSSH2_SFTP         *m_sftpSession;
    LIBSSH2_SFTP_HANDLE *m_sftpHandle;
};

#endif // UPLOAD_SFTP_H


upload_sftp.cpp

#include "upload_huainan.h"
#include
#include "log.h"

#ifdef WIN32
#include
#include
#else
#include
#include
#include
#include
#endif


CSftp::CSftp()
{
    m_session = NULL;
    m_sock = -1;
    m_sftpSession = NULL;
    m_sftpHandle = NULL;
}


CSftp::~CSftp()
{
    if (m_session != NULL)
    {
        libssh2_session_free(m_session);
        m_session = NULL;
    }
    DisConnHost();
    Fini();
}

bool CSftp::Init(QString remotePath ,QString ip /*= "10.11.22.34"*/, int port /*= 22*/, QString user /*= "test"*/, QString pwd /*= "test"*/)
{
    if (ip.length()<1 || user.length()<1 || pwd.length()<1 || port <1 || remotePath.length()<1 )
    {
        return false;
    }
    m_strIP = ip;
    m_nPort = port;
    m_strUser = user;
    m_strPwd = pwd;
    m_remotePath = remotePath;
    //初始化进程的时候调用
    //如果非0表示初始化失败!
    if (libssh2_init(0) != 0)
    {
        return false;
    }
    return true;
}


bool CSftp::Fini()
{
    libssh2_exit();
}


bool CSftp::ConnectToHost()
{
    //新建连接
    m_sock = socket(AF_INET, SOCK_STREAM, 0);
    sockaddr_in sin;
    sin.sin_family = AF_INET;
    sin.sin_port = htons(m_nPort);
    sin.sin_addr.s_addr = inet_addr(m_strIP.toStdString().c_str());
    if ( connect( m_sock, (sockaddr*)(&sin), sizeof(sockaddr_in) ) != 0 )
    {
        Log::trace(Log::Info,QObject::tr("socket failed to connect."));
        DisConnHost();
        return false;
    }

    //新建对话实例
    m_session = libssh2_session_init();
    if (!m_session)
    {
        Log::trace(Log::Info,QObject::tr("new session failed."));
        DisConnHost();
        return false;
    }

    //设置调用阻塞
    libssh2_session_set_blocking(m_session, 1);

    //进行握手
    if ( libssh2_session_handshake(m_session, m_sock) )
    {
        Log::trace(Log::Info,QObject::tr("Failure establishing SSH session."));
        DisConnHost();
        return false;
    }

    //获取主机指纹
    std::string fingerprint = libssh2_hostkey_hash(m_session, LIBSSH2_HOSTKEY_HASH_SHA1);
    std::string userauthlist = libssh2_userauth_list( m_session, m_strUser.toStdString().c_str(), (int)m_strUser.size() );

    int auth_pw = 0;
    if ( strstr( userauthlist.c_str(), "password") != NULL )
    {
        auth_pw |= 1;
    }
    if ( strstr( userauthlist.c_str(), "keyboard-interactive") != NULL )
    {
        auth_pw |= 2;
    }
    if ( strstr(userauthlist.c_str(), "publickey") != NULL)
    {
        auth_pw |= 4;
    }

    if (auth_pw & 1)
    {
        /* We could authenticate via password */
        //通过密码验证登陆用户身份
        if ( libssh2_userauth_password(m_session, m_strUser.toStdString().c_str(), m_strPwd.toStdString().c_str() ) )
        {
            Log::trace(Log::Info,QObject::tr("Authentication by password failed."));
            DisConnHost();
            return false;
        }
    }
    else if (auth_pw & 2)
    {
        /* Or via keyboard-interactive */
        //s_password = userPwd;
        //if (libssh2_userauth_keyboard_interactive(m_session, m_strUser.toStdString().c_str(), &S_KbdCallback) )
        //{
            Log::trace(Log::Info,QObject::tr("keyboard-interactive failed."));
            DisConnHost();
            return false;
        //}
    }
    else
    {
        Log::trace(Log::Info,QObject::tr("auth_pw else failed."));
        DisConnHost();
        return false;
    }
    m_sftpSession = libssh2_sftp_init(m_session);

    if (!m_sftpSession)
    {
        Log::trace(Log::Info,QObject::tr("Unable to init SFTP session."));
        DisConnHost();
        return false;
    }
    return true;
}

bool CSftp::CreateFile(const std::string fullPathFileName)
{
    if (!m_sftpSession || fullPathFileName.length()<1)
    {
        Log::trace(Log::Info,QObject::tr("CreateFile failure."));
        return false;
    }
    //向SFTP服务器发出新建文件请求
    m_sftpHandle = libssh2_sftp_open(m_sftpSession, fullPathFileName.c_str(),
        LIBSSH2_FXF_WRITE | LIBSSH2_FXF_CREAT | LIBSSH2_FXF_TRUNC,
        LIBSSH2_SFTP_S_IRUSR | LIBSSH2_SFTP_S_IWUSR |
        LIBSSH2_SFTP_S_IRGRP | LIBSSH2_SFTP_S_IROTH);

    if (!m_sftpHandle)
    {
        Log::trace(Log::Info,QObject::tr("Unable to open file with SFTP."));
        DisConnHost();
        return false;
    }
    return true;
}


bool CSftp::UploadSftp(const char * data, const int size,const std::string fullPathName,const std::string fileName)
{
    if (data == NULL || size <= 0)
    {
        return false;
    }
    if(!ConnectToHost())
    {
        return false;
    }
    if(!CreateDir(fullPathName))
    {
        return false;
    }
    if(!CreateFile(fullPathName + fileName))
    {
        return false;

    }

    ssize_t rc = 0;
    const char* ptr = data;
    size_t nsize = size;
    do {
        // 向服务器写数据,直到数据写完毕
        rc = libssh2_sftp_write(m_sftpHandle, ptr, nsize);
        if (rc < 0)
        {
            break;
        }
        ptr += rc;
        nsize -= rc;
    } while (nsize);

    libssh2_sftp_close(m_sftpHandle);
    libssh2_sftp_shutdown(m_sftpSession);
    DisConnHost();

    return true;
}


bool CSftp::DisConnHost()
{
    if( m_session )
    {
        libssh2_session_disconnect(m_session, "Bye bye, Thank you");
        libssh2_session_free(m_session);
        m_session = NULL;
    }
    if( m_sock != -1 )
    {
#ifdef WIN32
        closesocket(m_sock);
#else
        close(m_sock);
#endif
        m_sock = -1;
    }

    return true;
}

bool CSftp::CreateDir(const std::string fullPathName)
{
    if (!m_sftpSession || fullPathName.length()<1)
    {
        Log::trace(Log::Info,QObject::tr("CreateDir failed___1."));
        return false;
    }
    //向SFTP服务器发出新建文件请求

    m_sftpHandle = libssh2_sftp_opendir(m_sftpSession, fullPathName.c_str());

    if (!m_sftpHandle)
    {
        if(libssh2_sftp_mkdir(m_sftpSession, fullPathName.c_str(), S_IRWXU))
        {
            Log::trace(Log::Info,QObject::tr("CreateDir failed___2."));
            return false;
        }
        else
        {
            Log::trace(Log::Info,QObject::tr("CreateDir success."));
            return true;
        }
    }
    return true;
}


转载请备注出处!!否则,后果自负!!谢谢~  原创微博如下:http://blog.csdn.net/qnavy123

你可能感兴趣的:(ftp,和,sftp)