如何在c ++中使用scp libssh库从远程机器下载整个目录?

时间:2015-06-16 09:13:19

标签: c++ directory scp subdirectory libssh

我正在尝试下载远程计算机中的特定目录。我使用此代码从远程计算机下载了一个文件。

但我需要下载整个目录。我尝试了this代码。

但我无法复制整个目录。

// Indicate the which file going to be copied
scp = ssh_scp_new(session, SSH_SCP_READ, "/home/emres/test.xml");

if ( scp == NULL )
{
    EventLogger::LogMessage(true, "Error allocating scp session: scp == NULL");
    return SSH_ERROR;
}

rc = ssh_scp_init(scp);
if ( rc != SSH_OK )
{
    EventLogger::LogMessage(true, "Error initializing scp session: rc != SSH_OK");
    ssh_scp_free(scp);
    return rc;
}

rc = ssh_scp_pull_request(scp);
if ( rc != SSH_SCP_REQUEST_NEWFILE )
{
    EventLogger::LogMessage(true, "Error receiving information about file: rc != SSH_SCP_REQUEST_NEWFILE");
    return SSH_ERROR;
}

fileSize        = ssh_scp_request_get_size(scp);
filename        = strdup(ssh_scp_request_get_filename(scp));
filePermission  = ssh_scp_request_get_permissions(scp);

EventLogger::LogMessage(true, "Receiving file %s, size %d, permisssion %o", filename, fileSize, filePermission);

buffer = (char *)malloc(sizeof(char)*fileSize);

if ( buffer == NULL )
{
    EventLogger::LogMessage(true, "Memory allocation error!");
    return SSH_ERROR;
}

ssh_scp_accept_request(scp);
rc = ssh_scp_read(scp, buffer, sizeof(char)*fileSize);
if ( rc == SSH_ERROR )
{
    EventLogger::LogMessage(true, "Error receiving file data: rc == SSH_ERROR!");
    free(buffer);
    return rc;
}

char path[100];
sprintf(path, "D:/%s", filename);

if ( 0 < ( fd=open(path, O_RDWR | O_CREAT | O_TRUNC, filePermission) ) )
{
    write(fd, buffer, sizeof(char)*fileSize);
    close(fd);
}
else
{
    EventLogger::LogMessage(true, "Failed to open file!");
}

free(buffer);
free(filename);

ssh_scp_close(scp);
ssh_scp_free(scp);
return SSH_OK;

1 个答案:

答案 0 :(得分:0)

我知道这是一个老问题,但你仍然应该以递归模式打开会话并使用文件夹的正确路径,而不是文件。

scp = ssh_scp_new(session, SSH_SCP_READ | SSH_SCP_RECURSIVE, "/home/emres");