libssh2

Форк
0
/
sftpdir.c 
310 строк · 8.8 Кб
1
/* Copyright (C) The libssh2 project and its contributors.
2
 *
3
 * Sample doing an SFTP directory listing.
4
 *
5
 * The sample code has default values for host name, user name, password and
6
 * path, but you can specify them on the command line like:
7
 *
8
 * $ ./sftpdir 192.168.0.1 user password /tmp/secretdir
9
 *
10
 * SPDX-License-Identifier: BSD-3-Clause
11
 */
12

13
#include "libssh2_setup.h"
14
#include <libssh2.h>
15
#include <libssh2_sftp.h>
16

17
#ifdef HAVE_SYS_SOCKET_H
18
#include <sys/socket.h>
19
#endif
20
#ifdef HAVE_UNISTD_H
21
#include <unistd.h>
22
#endif
23
#ifdef HAVE_NETINET_IN_H
24
#include <netinet/in.h>
25
#endif
26
#ifdef HAVE_ARPA_INET_H
27
#include <arpa/inet.h>
28
#endif
29

30
#include <stdio.h>
31
#include <string.h>
32

33
#if defined(_MSC_VER)
34
#define LIBSSH2_FILESIZE_MASK "I64u"
35
#else
36
#define LIBSSH2_FILESIZE_MASK "llu"
37
#endif
38

39
static const char *pubkey = "/home/username/.ssh/id_rsa.pub";
40
static const char *privkey = "/home/username/.ssh/id_rsa";
41
static const char *username = "username";
42
static const char *password = "password";
43
static const char *sftppath = "/tmp/secretdir";
44

45
static void kbd_callback(const char *name, int name_len,
46
                         const char *instruction, int instruction_len,
47
                         int num_prompts,
48
                         const LIBSSH2_USERAUTH_KBDINT_PROMPT *prompts,
49
                         LIBSSH2_USERAUTH_KBDINT_RESPONSE *responses,
50
                         void **abstract)
51
{
52
    (void)name;
53
    (void)name_len;
54
    (void)instruction;
55
    (void)instruction_len;
56
    if(num_prompts == 1) {
57
        responses[0].text = strdup(password);
58
        responses[0].length = (unsigned int)strlen(password);
59
    }
60
    (void)prompts;
61
    (void)abstract;
62
} /* kbd_callback */
63

64
int main(int argc, char *argv[])
65
{
66
    uint32_t hostaddr;
67
    libssh2_socket_t sock;
68
    int i, auth_pw = 0;
69
    struct sockaddr_in sin;
70
    const char *fingerprint;
71
    char *userauthlist;
72
    int rc;
73
    LIBSSH2_SESSION *session = NULL;
74
    LIBSSH2_SFTP *sftp_session;
75
    LIBSSH2_SFTP_HANDLE *sftp_handle;
76

77
#ifdef _WIN32
78
    WSADATA wsadata;
79

80
    rc = WSAStartup(MAKEWORD(2, 0), &wsadata);
81
    if(rc) {
82
        fprintf(stderr, "WSAStartup failed with error: %d\n", rc);
83
        return 1;
84
    }
85
#endif
86

87
    if(argc > 1) {
88
        hostaddr = inet_addr(argv[1]);
89
    }
90
    else {
91
        hostaddr = htonl(0x7F000001);
92
    }
93
    if(argc > 2) {
94
        username = argv[2];
95
    }
96
    if(argc > 3) {
97
        password = argv[3];
98
    }
99
    if(argc > 4) {
100
        sftppath = argv[4];
101
    }
102

103
    rc = libssh2_init(0);
104
    if(rc) {
105
        fprintf(stderr, "libssh2 initialization failed (%d)\n", rc);
106
        return 1;
107
    }
108

109
    /*
110
     * The application code is responsible for creating the socket
111
     * and establishing the connection
112
     */
113
    sock = socket(AF_INET, SOCK_STREAM, 0);
114
    if(sock == LIBSSH2_INVALID_SOCKET) {
115
        fprintf(stderr, "failed to create socket.\n");
116
        goto shutdown;
117
    }
118

119
    sin.sin_family = AF_INET;
120
    sin.sin_port = htons(22);
121
    sin.sin_addr.s_addr = hostaddr;
122
    if(connect(sock, (struct sockaddr*)(&sin), sizeof(struct sockaddr_in))) {
123
        fprintf(stderr, "failed to connect.\n");
124
        goto shutdown;
125
    }
126

127
    /* Create a session instance */
128
    session = libssh2_session_init();
129
    if(!session) {
130
        fprintf(stderr, "Could not initialize SSH session.\n");
131
        goto shutdown;
132
    }
133

134
    /* ... start it up. This will trade welcome banners, exchange keys,
135
     * and setup crypto, compression, and MAC layers
136
     */
137
    rc = libssh2_session_handshake(session, sock);
138
    if(rc) {
139
        fprintf(stderr, "Failure establishing SSH session: %d\n", rc);
140
        goto shutdown;
141
    }
142

143
    /* At this point we have not yet authenticated.  The first thing to do
144
     * is check the hostkey's fingerprint against our known hosts Your app
145
     * may have it hard coded, may go to a file, may present it to the
146
     * user, that's your call
147
     */
148
    fingerprint = libssh2_hostkey_hash(session, LIBSSH2_HOSTKEY_HASH_SHA1);
149
    fprintf(stderr, "Fingerprint: ");
150
    for(i = 0; i < 20; i++) {
151
        fprintf(stderr, "%02X ", (unsigned char)fingerprint[i]);
152
    }
153
    fprintf(stderr, "\n");
154

155
    /* check what authentication methods are available */
156
    userauthlist = libssh2_userauth_list(session, username,
157
                                         (unsigned int)strlen(username));
158
    if(userauthlist) {
159
        fprintf(stderr, "Authentication methods: %s\n", userauthlist);
160
        if(strstr(userauthlist, "password")) {
161
            auth_pw |= 1;
162
        }
163
        if(strstr(userauthlist, "keyboard-interactive")) {
164
            auth_pw |= 2;
165
        }
166
        if(strstr(userauthlist, "publickey")) {
167
            auth_pw |= 4;
168
        }
169

170
        /* check for options */
171
        if(argc > 5) {
172
            if((auth_pw & 1) && !strcmp(argv[5], "-p")) {
173
                auth_pw = 1;
174
            }
175
            if((auth_pw & 2) && !strcmp(argv[5], "-i")) {
176
                auth_pw = 2;
177
            }
178
            if((auth_pw & 4) && !strcmp(argv[5], "-k")) {
179
                auth_pw = 4;
180
            }
181
        }
182

183
        if(auth_pw & 1) {
184
            /* We could authenticate via password */
185
            if(libssh2_userauth_password(session, username, password)) {
186
                fprintf(stderr, "Authentication by password failed.\n");
187
                goto shutdown;
188
            }
189
        }
190
        else if(auth_pw & 2) {
191
            /* Or via keyboard-interactive */
192
            if(libssh2_userauth_keyboard_interactive(session, username,
193
                                                     &kbd_callback) ) {
194
                fprintf(stderr,
195
                        "Authentication by keyboard-interactive failed.\n");
196
                goto shutdown;
197
            }
198
            else {
199
                fprintf(stderr,
200
                        "Authentication by keyboard-interactive succeeded.\n");
201
            }
202
        }
203
        else if(auth_pw & 4) {
204
            /* Or by public key */
205
            if(libssh2_userauth_publickey_fromfile(session, username,
206
                                                   pubkey, privkey,
207
                                                   password)) {
208
                fprintf(stderr, "Authentication by public key failed.\n");
209
                goto shutdown;
210
            }
211
            else {
212
                fprintf(stderr, "Authentication by public key succeeded.\n");
213
            }
214
        }
215
        else {
216
            fprintf(stderr, "No supported authentication methods found.\n");
217
            goto shutdown;
218
        }
219
    }
220

221
    fprintf(stderr, "libssh2_sftp_init().\n");
222
    sftp_session = libssh2_sftp_init(session);
223

224
    if(!sftp_session) {
225
        fprintf(stderr, "Unable to init SFTP session\n");
226
        goto shutdown;
227
    }
228

229
    /* Since we have not set non-blocking, tell libssh2 we are blocking */
230
    libssh2_session_set_blocking(session, 1);
231

232
    fprintf(stderr, "libssh2_sftp_opendir().\n");
233
    /* Request a dir listing via SFTP */
234
    sftp_handle = libssh2_sftp_opendir(sftp_session, sftppath);
235
    if(!sftp_handle) {
236
        fprintf(stderr, "Unable to open dir with SFTP\n");
237
        goto shutdown;
238
    }
239

240
    fprintf(stderr, "libssh2_sftp_opendir() is done, now receive listing.\n");
241
    do {
242
        char mem[512];
243
        char longentry[512];
244
        LIBSSH2_SFTP_ATTRIBUTES attrs;
245

246
        /* loop until we fail */
247
        rc = libssh2_sftp_readdir_ex(sftp_handle, mem, sizeof(mem),
248
                                     longentry, sizeof(longentry), &attrs);
249
        if(rc > 0) {
250
            /* rc is the length of the file name in the mem
251
               buffer */
252

253
            if(longentry[0] != '\0') {
254
                printf("%s\n", longentry);
255
            }
256
            else {
257
                if(attrs.flags & LIBSSH2_SFTP_ATTR_PERMISSIONS) {
258
                    /* this should check what permissions it
259
                       is and print the output accordingly */
260
                    printf("--fix----- ");
261
                }
262
                else {
263
                    printf("---------- ");
264
                }
265

266
                if(attrs.flags & LIBSSH2_SFTP_ATTR_UIDGID) {
267
                    printf("%4d %4d ", (int) attrs.uid, (int) attrs.gid);
268
                }
269
                else {
270
                    printf("   -    - ");
271
                }
272

273
                if(attrs.flags & LIBSSH2_SFTP_ATTR_SIZE) {
274
                    printf("%8" LIBSSH2_FILESIZE_MASK " ", attrs.filesize);
275
                }
276

277
                printf("%s\n", mem);
278
            }
279
        }
280
        else {
281
            break;
282
        }
283

284
    } while(1);
285

286
    libssh2_sftp_closedir(sftp_handle);
287
    libssh2_sftp_shutdown(sftp_session);
288

289
shutdown:
290

291
    if(session) {
292
        libssh2_session_disconnect(session, "Normal Shutdown");
293
        libssh2_session_free(session);
294
    }
295

296
    if(sock != LIBSSH2_INVALID_SOCKET) {
297
        shutdown(sock, 2);
298
        LIBSSH2_SOCKET_CLOSE(sock);
299
    }
300

301
    fprintf(stderr, "all done\n");
302

303
    libssh2_exit();
304

305
#ifdef _WIN32
306
    WSACleanup();
307
#endif
308

309
    return 0;
310
}
311

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.