[英]SCP functionality in C. library list: libCurl, libssh or libssh2
I had a problem a while ago writing a program in C which utilizes scp to transfer and download files to a server. 前段时间我遇到了一个问题,该问题使用C语言编写了一个程序,该程序利用scp将文件传输并下载到服务器。 The program had to be written for windows.
该程序必须为Windows编写。 Initially I attempted to use the libCurl library which then I encountered different problems and it didn't work well.
最初,我尝试使用libCurl库,然后遇到了不同的问题,并且运行不正常。 After switching to libssh and the issue was fixed.
切换到libssh之后,此问题已解决。
I'm posting a segment of my sample code which downloads a file from a remote server. 我正在发布我的示例代码的一部分,该部分从远程服务器下载文件。 hopefully this could be helpful to anyone who lands here.
希望这对任何登陆这里的人都有帮助。
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;
}
Switched to lilbssh. 切换到lilbssh。 You can manage the scp stages manually and works ok.
您可以手动管理scp阶段,并且可以正常工作。 However, I don't know if libssh2 is better or not.
但是,我不知道libssh2是否更好。 Any comments?
任何意见?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.