How can I download entire directory from remote machine with using scp libssh library in c++?

1.3k views Asked by At

I am trying to download specific directory in my remote machine. I downloaded a file from remote machine with this code.

But I need to download entire directories. I tried this code.

But I was not able to copy an entire directory.

// 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

There are 1 answers

0
rightaway717 On

I know that is a old question, but still you should open a session in recursive mode and use correct path to the folder, not to the file.

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