编辑
我有一个问题,前一段时间写一个程序,在C中利用scp传输和下载文件到服务器。这个程序必须是为windows编写的。最初我尝试使用libCurl库,然后我遇到了不同的问题,它不能很好地工作。切换到libssh后,问题得到了解决。
我发布了一段从远程服务器下载文件的示例代码。希望这能对任何来到这里的人有所帮助。
int scp_recv_file(ssh_session in_session,
char * in_remotefile, char * in_localfile)
{
ssh_scp t_scp = NULL;
int t_rc, t_filesize, t_filemode = -1;
char *t_filename, *t_buffer;
t_scp = ssh_scp_new
(in_session, SSH_SCP_READ | SSH_SCP_RECURSIVE, in_remotefile);
if (t_scp == NULL)
{
fprintf(stderr, "Error allocating scp session: %s\n",
ssh_get_error(in_session));
return SSH_ERROR;
}
t_rc = ssh_scp_init(t_scp);
if (t_rc != SSH_OK)
{
fprintf(stderr, "Error initializing scp session: %s\n",
ssh_get_error(in_session));
ssh_scp_free(t_scp);
return t_rc;
}
//create ssh pull a file request
t_rc = ssh_scp_pull_request(t_scp);
if (t_rc != SSH_SCP_REQUEST_NEWFILE)
{
fprintf(stderr, "Error receiving information about file: %s\n",
ssh_get_error(in_session));
return SSH_ERROR;
}
t_filesize = ssh_scp_request_get_size(t_scp);
t_filename = strdup(ssh_scp_request_get_filename(t_scp));
t_filemode = ssh_scp_request_get_permissions(t_scp);
printf("Receiving file %s, size %d, permisssions 0%o\n",
t_filename, t_filesize, t_filemode);
t_buffer = malloc(t_filesize);
if (t_buffer == NULL)
{
fprintf(stderr, "Memory allocation error\n");
return SSH_ERROR;
}
ssh_scp_accept_request(t_scp);
t_rc = ssh_scp_read(t_scp, t_buffer, t_filesize);
if (t_rc == SSH_ERROR)
{
fprintf(stderr, "Error receiving file data: %s\n",
ssh_get_error(in_session));
free(t_buffer);
return t_rc;
}
printf("Done\n");
//write buffer to file
writeToFile(in_localfile, t_buffer, t_filesize);
//write(1, buffer, size);
//free allocated memory
free(t_buffer);
free(t_filename);
t_rc = ssh_scp_pull_request(t_scp);
if (t_rc != SSH_SCP_REQUEST_EOF)
{
fprintf(stderr, "Unexpected request: %s\n",
ssh_get_error(in_session));
return SSH_ERROR;
}
//close scp and free
ssh_scp_close(t_scp);
ssh_scp_free(t_scp);
return SSH_OK;
}
字符串
2条答案
按热度按时间atmip9wb1#
切换到lilbssh。您可以手动管理scp阶段和工作正常。但是,我不知道libssh2是否更好。有什么意见吗?
rkue9o1l2#
libssh 2有所有过时的密钥交换算法,如ssh-rsa和dss。你应该很擅长libssh。