用libssh2的接口来实现获取远端文件。步骤如下:
1. 创建socket
2. ssh 握手
1)libssh2_session_init
2)libssh2_session_handshake
3)libssh2_userauth_password
3. sftp 连接
libssh2_sftp_init
4. 获取文件
1)libssh2_sftp_open
2)libssh2_sftp_fstat
3)libssh2_sftp_read
代码如下:
#ifndef SFTP_H
#define SFTP_H
#include <string>
using namespace std;
class Sftp
{
public:
int Init(const char *pIp, const char *pUser, const char *pPwd);
void Release();
int GetFile(const char *pName, char *&pData, int &nLen);
private:
string m_strIp;
string m_strUser;
string m_strPasswd;
};
#endif
#include "Sftp.h"
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <libssh2.h>
#include <libssh2_sftp.h>
#include <stdlib.h>
int Sftp::Init(char* pIp, char* pUser, char* pPwd)
{
m_strIp = pIp;
m_strUser = pUser;
m_strPasswd = pPwd;
int nRet = libssh2_init(0);
if (nRet != 0)
return -1;
return 0;
}
void Sftp::Release()
{
libssh2_exit();
}
int Sftp::GetFile(const char* pName, char*& pData, int& nLen)
{
int nRet;
int nFd;
socklen_t nAddrLen;
struct sockaddr_in addr;
LIBSSH2_SESSION* pSshSession;
LIBSSH2_SFTP* pSftpSession;
LIBSSH2_SFTP_HANDLE* pSftpHandle;
LIBSSH2_SFTP_ATTRIBUTES att = {0};
pData = NULL;
nLen = 0;
// socket 创建连接
nFd = socket(AF_INET, SOCK_STREAM, 0);
if (nFd == -1)
{
nRet = -10;
goto EXIT;
}
addr.sin_family = AF_INET;
addr.sin_port = htons(22);
addr.sin_addr.s_addr = inet_addr(m_strIp.c_str());
nAddrLen = sizeof(addr);
if (connect(nFd, (struct sockaddr*)(&addr), nAddrLen) != 0)
{
nRet = -11;
goto EXIT;
}
// ssh session 创建,连接
pSshSession = libssh2_session_init();
if (pSshSession == NULL)
{
nRet = -20;
goto EXIT;
}
nRet = libssh2_session_handshake(pSshSession, nFd);
if (nRet != 0)
{
nRet = -21;
goto EXIT;
}
nRet = libssh2_userauth_password(pSshSession,
m_strUser.c_str(),
m_strPasswd.c_str());
if (nRet != 0)
{
nRet = -22;
goto EXIT;
}
// sftp
pSftpSession = libssh2_sftp_init(pSshSession);
if (pSftpSession == NULL)
{
nRet = -30;
goto EXIT;
}
pSftpHandle = libssh2_sftp_open(pSftpSession, pName, LIBSSH2_FXF_READ, 0);
if (pSftpHandle == NULL)
{
nRet = -31;
goto EXIT;
}
// 获取文件大小
if (libssh2_sftp_fstat(pSftpHandle, &att) != 0)
{
nRet = -32;
goto EXIT;
}
// read
nLen = att.filesize;
pData = (char*)malloc(nLen);
if (pData == NULL)
{
nRet = -40;
goto EXIT;
}
nRet = libssh2_sftp_read(pSftpHandle, pData, nLen);
if (nRet <= 0)
{
nRet = -41;
goto EXIT;
}
libssh2_sftp_close(pSftpHandle);
libssh2_sftp_shutdown(pSftpSession);
nRet = 0;
EXIT:
if (pSshSession)
{
libssh2_session_disconnect(pSshSession, "Normal Shutdown");
libssh2_session_free(pSshSession);
}
if (nFd)
close(nFd);
return nRet;
}
网友评论