使用sshlib scp函数将jpg和h264文件从远程服务器复制到Windows

时间:2019-02-21 02:50:18

标签: c++ visual-studio-2012 scp libssh

我需要使用libsshscp协议从远程位置下载目录。该目录中包含音频,视频和一些文本文件。使用以下代码,我试图借助scp函数从目录中libssh scp这些文件,但是它正在下载一些垃圾文件。如果我尝试获取txt文件,它会将数据复制到某个随机名称的文件中,例如oyø,但在Windows计算机的给定路径中没有扩展名。谁能指导我做错了什么以及如何修复它以使文件传输?或者,是否还有其他方法可以使用libssh下载这些文件?

  #include <iostream>
  #include <string>
  #include <libssh.h>
  #include <stdlib.h>
  #include <fstream> 
  #include <stdio.h>
  #include <fcntl.h>
  #include <sstream>
  #include <io.h>


static int fetch_files(ssh_session session)
{
    int size;
    int mode;
    int rc;
    int fd;
    ssh_scp scp = ssh_scp_new(session,
                              SSH_SCP_READ | SSH_SCP_RECURSIVE,
                              "/data/misc/qmmf/snapshot_01.jpg");

    if (scp == NULL)
    {
        std::cout << "Error allocating scp session: scp == NULL";
        return -1;
    }

    rc = ssh_scp_init(scp);
    if (rc != SSH_OK)
    {
        std::cout << "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)
    {
        cout << "Error receiving information about file: rc != SSH_SCP_REQUEST_NEWFILE";
        return -3;
    }

    int fileSize = ssh_scp_request_get_size(scp);
    string filename = _strdup(ssh_scp_request_get_filename(scp));
    int filePermission = ssh_scp_request_get_permissions(scp);
    cout << "fileSize" << fileSize << endl;
    cout << "filename" << filename << endl;
    cout << "filePermission" << filePermission << endl;

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

    if (buffer1 == NULL)
    {
        cout << "Memory allocation error!";
        return SSH_ERROR;
    }

    ssh_scp_accept_request(scp);
    rc = ssh_scp_read(scp, buffer1, sizeof(char) * fileSize);
    if (rc == SSH_ERROR)
    {
        cout << "Error receiving file data: rc == SSH_ERROR!";
        free(buffer1);
        return rc;
    }

    char path[10000];
    sprintf_s(path, "C:\Documents/%s", filename);

    if (0 < (fd = open(path, O_RDWR | O_CREAT | O_TRUNC, filePermission)))
    {
        write(fd, buffer1, sizeof(char) * fileSize);
        close(fd);
    }
    else
    {
        cout << "Failed to open file!";
    }
    return 0;
}

0 个答案:

没有答案