1 /***************************************************************************
3 * Project ___| | | | _ \| |
5 * | (__| |_| | _ <| |___
6 * \___|\___/|_| \_\_____|
8 * Copyright (C) 1998 - 2016, Daniel Stenberg, <daniel@haxx.se>, et al.
10 * This software is licensed as described in the file COPYING, which
11 * you should have received as part of this distribution. The terms
12 * are also available at https://curl.haxx.se/docs/copyright.html.
14 * You may opt to use, copy, modify, merge, publish, distribute and/or sell
15 * copies of the Software, and permit persons to whom the Software is
16 * furnished to do so, under the terms of the COPYING file.
18 * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
19 * KIND, either express or implied.
21 ***************************************************************************/
23 * Gets a file using an SFTP URL.
29 #include <curl/curl.h>
31 /* define this to switch off the use of ssh-agent in this program */
32 #undef DISABLE_SSH_AGENT
35 * This is an example showing how to get a single file from an SFTP server.
36 * It delays the actual destination file creation until the first write
37 * callback so that it won't create an empty file in case the remote file
38 * doesn't exist or something else fails.
46 static size_t my_fwrite(void *buffer, size_t size, size_t nmemb,
49 struct FtpFile *out=(struct FtpFile *)stream;
50 if(out && !out->stream) {
51 /* open file for writing */
52 out->stream=fopen(out->filename, "wb");
54 return -1; /* failure, can't open file to write */
56 return fwrite(buffer, size, nmemb, out->stream);
64 struct FtpFile ftpfile={
65 "yourfile.bin", /* name to store the file as if successful */
69 curl_global_init(CURL_GLOBAL_DEFAULT);
71 curl = curl_easy_init();
74 * You better replace the URL with one that works!
76 curl_easy_setopt(curl, CURLOPT_URL,
77 "sftp://user@server/home/user/file.txt");
78 /* Define our callback to get called when there's data to be written */
79 curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, my_fwrite);
80 /* Set a pointer to our struct to pass to the callback */
81 curl_easy_setopt(curl, CURLOPT_WRITEDATA, &ftpfile);
83 #ifndef DISABLE_SSH_AGENT
84 /* We activate ssh agent. For this to work you need
85 to have ssh-agent running (type set | grep SSH_AGENT to check) or
86 pageant on Windows (there is an icon in systray if so) */
87 curl_easy_setopt(curl, CURLOPT_SSH_AUTH_TYPES, CURLSSH_AUTH_AGENT);
90 /* Switch on full protocol/debug output */
91 curl_easy_setopt(curl, CURLOPT_VERBOSE, 1L);
93 res = curl_easy_perform(curl);
96 curl_easy_cleanup(curl);
100 fprintf(stderr, "curl told us %d\n", res);
105 fclose(ftpfile.stream); /* close the local file */
107 curl_global_cleanup();