1、目标
近期项目做文件传输都是基于sftp,这里我选择了libcurl。不过要注意的是libcurl默认下并不支持SFTP,需要在编译的时候添加libssh2依赖项,而libssh2又依赖于openssl和zlib。注意讲一下目录,下载上传网上很多。
2、编译库
由于一些基建库的原因,我自己的c++环境用的是vs2010, 我的curl库。
这里我推荐链接: 柴承训编译libcurl的博客
3、获取linux目录
这里都是基于libcurl官方提供的example。
注意点1
curl_easy_setopt(curl, CURLOPT_URL,“sftp://127.0.0.1:22/home/”);
sftp://127.0.0.1:22/usr/ 定位到目录一定记得加斜杠,否则指定就不同了。
注意点2
是否使用 CURLOPT_DIRLISTONLY,如果你单纯的只想拿到目录的名称请调用curl_easy_setopt(curl, CURLOPT_DIRLISTONLY, 1);
如果,你想获取所有的信息,请千万不要加这一句;
调用CURLOPT_DIRLISTONLY结果:
..
user
docker
chry
dmdba
.
不调用CURLOPT_DIRLISTONLY结果:
drwxrwxr-x 25 root root 4096 Nov 3 10:45 ..
drwx------ 42 user user 4096 Nov 17 19:11 user
drwxrwxrwx 11 root root 4096 Nov 8 16:59 docker
drwxr-xr-x 3 root root 4096 Jul 28 17:29 chry
drwxr-xr-x 3 root root 4096 Nov 2 13:53 dmdba
drwxr-xr-x 6 root root 4096 Nov 2 11:13 .
获取结果解析
整体代码如下:
#include <stdio.h>
#include <curl/curl.h>
#undef DISABLE_SSH_AGENT
struct FtpFile {
const char* filename;
FILE* stream;
};
static size_t my_fwrite(void* buffer, size_t size, size_t nmemb,
void* stream)
{
struct FtpFile* out = (struct FtpFile*)stream;
if (!out->stream) {
out->stream = fopen(out->filename, "wb");
if (!out->stream)
return -1;
}
return fwrite(buffer, size, nmemb, out->stream);
}
int main(void)
{
CURL* curl;
CURLcode res;
struct FtpFile ftpfile = {
"D:\\download\\1.txt",
NULL
};
curl_global_init(CURL_GLOBAL_DEFAULT);
curl = curl_easy_init();
if (curl) {
curl_easy_setopt(curl, CURLOPT_URL,
"sftp://127.0.0.1:22/home/");
curl_easy_setopt(curl, CURLOPT_USERPWD, "username:password");
curl_easy_setopt(curl, CURLOPT_USE_SSL, CURLUSESSL_TRY);
curl_easy_setopt(curl, CURLOPT_VERBOSE, 1);
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, my_fwrite);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &ftpfile);
#ifndef DISABLE_SSH_AGENT
curl_easy_setopt(curl, CURLOPT_SSH_AUTH_TYPES, CURLSSH_AUTH_PASSWORD);
#endif
curl_easy_setopt(curl, CURLOPT_VERBOSE, 1L);
res = curl_easy_perform(curl);
curl_easy_cleanup(curl);
if (CURLE_OK != res) {
fprintf(stderr, "curl told us %d\n", res);
}
}
if (ftpfile.stream)
fclose(ftpfile.stream);
curl_global_cleanup();
return 0;
}
4、下载上传文件
这个网上的例子很多,推荐一个,SFTP+FTP上传下载。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)