curl sftp libcurl 功能使用

╰半夏微凉° 2022-03-16 09:36 638阅读 0赞
  1. #include <curl/curl.h>
  2. #undef DISABLE_SSH_AGENT
  3. struct FtpFile {
  4. const char *filename;
  5. FILE *stream;
  6. };
  7. static size_t my_fwrite(void *buffer, size_t size, size_t nmemb,
  8. void *stream)
  9. {
  10. struct FtpFile *out = (struct FtpFile *)stream;
  11. if(!out->stream) {
  12. /* open file for writing */
  13. out->stream = fopen(out->filename, "wb");
  14. if(!out->stream)
  15. return -1; /* failure, can't open file to write */
  16. }
  17. return fwrite(buffer, size, nmemb, out->stream);
  18. }
  19. //sftp协议
  20. void fileLoadSftp()
  21. {
  22. CURL *curl;
  23. CURLcode res;
  24. char *filename = ui->lineEdit_path->text().toLatin1().data(); //本地文件名
  25. QString remote = "sftp://user:password@example.com/etc/issue";
  26. char *remote_url = remote.toLatin1().data(); //服务器路径
  27. struct FtpFile ftpfile =
  28. {
  29. filename, /* name to store the file as if successful */
  30. NULL
  31. };
  32. curl_global_init(CURL_GLOBAL_DEFAULT);
  33. curl = curl_easy_init();
  34. if(curl) {
  35. /*
  36. * You better replace the URL with one that works!
  37. * sftp://user:password@example.com/etc/issue - This specifies the file /etc/issue
  38. */
  39. curl_easy_setopt(curl, CURLOPT_URL, remote_url);
  40. /* Define our callback to get called when there's data to be written */
  41. curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, my_fwrite);
  42. /* Set a pointer to our struct to pass to the callback */
  43. curl_easy_setopt(curl, CURLOPT_WRITEDATA, &ftpfile);
  44. #ifndef DISABLE_SSH_AGENT
  45. /* We activate ssh agent. For this to work you need
  46. to have ssh-agent running (type set | grep SSH_AGENT to check) or
  47. pageant on Windows (there is an icon in systray if so) */
  48. curl_easy_setopt(curl, CURLOPT_SSH_AUTH_TYPES, CURLSSH_AUTH_PASSWORD);
  49. #endif
  50. /* Switch on full protocol/debug output */
  51. curl_easy_setopt(curl, CURLOPT_VERBOSE, 1L);
  52. res = curl_easy_perform(curl);
  53. /* always cleanup */
  54. curl_easy_cleanup(curl);
  55. if(CURLE_OK != res) {
  56. /* we failed */
  57. fprintf(stderr, "curl told us %d\n", res);
  58. }
  59. }
  60. if(ftpfile.stream)
  61. fclose(ftpfile.stream); /* close the local file */
  62. curl_global_cleanup();
  63. }

发表评论

表情:
评论列表 (有 0 条评论,638人围观)

还没有评论,来说两句吧...

相关阅读