libssh2

Форк
0
/
sftpdir_nonblock.c 
250 строк · 6.7 Кб
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_nonblock 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

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

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

44
int main(int argc, char *argv[])
45
{
46
    uint32_t hostaddr;
47
    libssh2_socket_t sock;
48
    int i, auth_pw = 1;
49
    struct sockaddr_in sin;
50
    const char *fingerprint;
51
    int rc;
52
    LIBSSH2_SESSION *session = NULL;
53
    LIBSSH2_SFTP *sftp_session;
54
    LIBSSH2_SFTP_HANDLE *sftp_handle;
55

56
#ifdef _WIN32
57
    WSADATA wsadata;
58

59
    rc = WSAStartup(MAKEWORD(2, 0), &wsadata);
60
    if(rc) {
61
        fprintf(stderr, "WSAStartup failed with error: %d\n", rc);
62
        return 1;
63
    }
64
#endif
65

66
    if(argc > 1) {
67
        hostaddr = inet_addr(argv[1]);
68
    }
69
    else {
70
        hostaddr = htonl(0x7F000001);
71
    }
72
    if(argc > 2) {
73
        username = argv[2];
74
    }
75
    if(argc > 3) {
76
        password = argv[3];
77
    }
78
    if(argc > 4) {
79
        sftppath = argv[4];
80
    }
81

82
    rc = libssh2_init(0);
83
    if(rc) {
84
        fprintf(stderr, "libssh2 initialization failed (%d)\n", rc);
85
        return 1;
86
    }
87

88
    /*
89
     * The application code is responsible for creating the socket
90
     * and establishing the connection
91
     */
92
    sock = socket(AF_INET, SOCK_STREAM, 0);
93
    if(sock == LIBSSH2_INVALID_SOCKET) {
94
        fprintf(stderr, "failed to create socket.\n");
95
        goto shutdown;
96
    }
97

98
    sin.sin_family = AF_INET;
99
    sin.sin_port = htons(22);
100
    sin.sin_addr.s_addr = hostaddr;
101
    if(connect(sock, (struct sockaddr*)(&sin), sizeof(struct sockaddr_in))) {
102
        fprintf(stderr, "failed to connect.\n");
103
        goto shutdown;
104
    }
105

106
    /* Create a session instance */
107
    session = libssh2_session_init();
108
    if(!session) {
109
        fprintf(stderr, "Could not initialize SSH session.\n");
110
        goto shutdown;
111
    }
112

113
    /* Since we have set non-blocking, tell libssh2 we are non-blocking */
114
    libssh2_session_set_blocking(session, 0);
115

116
    /* ... start it up. This will trade welcome banners, exchange keys,
117
     * and setup crypto, compression, and MAC layers
118
     */
119
    while((rc = libssh2_session_handshake(session, sock)) ==
120
          LIBSSH2_ERROR_EAGAIN);
121
    if(rc) {
122
        fprintf(stderr, "Failure establishing SSH session: %d\n", rc);
123
        goto shutdown;
124
    }
125

126
    /* At this point we have not yet authenticated.  The first thing to do
127
     * is check the hostkey's fingerprint against our known hosts Your app
128
     * may have it hard coded, may go to a file, may present it to the
129
     * user, that's your call
130
     */
131
    fingerprint = libssh2_hostkey_hash(session, LIBSSH2_HOSTKEY_HASH_SHA1);
132
    fprintf(stderr, "Fingerprint: ");
133
    for(i = 0; i < 20; i++) {
134
        fprintf(stderr, "%02X ", (unsigned char)fingerprint[i]);
135
    }
136
    fprintf(stderr, "\n");
137

138
    if(auth_pw) {
139
        /* We could authenticate via password */
140
        while((rc = libssh2_userauth_password(session, username, password)) ==
141
              LIBSSH2_ERROR_EAGAIN);
142
        if(rc) {
143
            fprintf(stderr, "Authentication by password failed.\n");
144
            goto shutdown;
145
        }
146
    }
147
    else {
148
        /* Or by public key */
149
        while((rc = libssh2_userauth_publickey_fromfile(session, username,
150
                                                        pubkey, privkey,
151
                                                        password)) ==
152
              LIBSSH2_ERROR_EAGAIN);
153
        if(rc) {
154
            fprintf(stderr, "Authentication by public key failed.\n");
155
            goto shutdown;
156
        }
157
    }
158

159
    fprintf(stderr, "libssh2_sftp_init().\n");
160
    do {
161
        sftp_session = libssh2_sftp_init(session);
162

163
        if(!sftp_session &&
164
           libssh2_session_last_errno(session) != LIBSSH2_ERROR_EAGAIN) {
165
            fprintf(stderr, "Unable to init SFTP session\n");
166
            goto shutdown;
167
        }
168
    } while(!sftp_session);
169

170
    fprintf(stderr, "libssh2_sftp_opendir().\n");
171
    /* Request a dir listing via SFTP */
172
    do {
173
        sftp_handle = libssh2_sftp_opendir(sftp_session, sftppath);
174

175
        if(!sftp_handle &&
176
           libssh2_session_last_errno(session) != LIBSSH2_ERROR_EAGAIN) {
177
            fprintf(stderr, "Unable to open dir with SFTP\n");
178
            goto shutdown;
179
        }
180
    } while(!sftp_handle);
181

182
    fprintf(stderr, "libssh2_sftp_opendir() is done, now receive listing.\n");
183
    do {
184
        char mem[512];
185
        LIBSSH2_SFTP_ATTRIBUTES attrs;
186

187
        /* loop until we fail */
188
        while((rc = libssh2_sftp_readdir(sftp_handle, mem, sizeof(mem),
189
                                         &attrs)) == LIBSSH2_ERROR_EAGAIN);
190
        if(rc > 0) {
191
            /* rc is the length of the file name in the mem
192
               buffer */
193

194
            if(attrs.flags & LIBSSH2_SFTP_ATTR_PERMISSIONS) {
195
                /* this should check what permissions it
196
                   is and print the output accordingly */
197
                printf("--fix----- ");
198
            }
199
            else {
200
                printf("---------- ");
201
            }
202

203
            if(attrs.flags & LIBSSH2_SFTP_ATTR_UIDGID) {
204
                printf("%4d %4d ", (int) attrs.uid, (int) attrs.gid);
205
            }
206
            else {
207
                printf("   -    - ");
208
            }
209

210
            if(attrs.flags & LIBSSH2_SFTP_ATTR_SIZE) {
211
                printf("%8" LIBSSH2_FILESIZE_MASK " ", attrs.filesize);
212
            }
213

214
            printf("%s\n", mem);
215
        }
216
        else if(rc == LIBSSH2_ERROR_EAGAIN) {
217
            /* blocking */
218
            fprintf(stderr, "Blocking\n");
219
        }
220
        else {
221
            break;
222
        }
223

224
    } while(1);
225

226
    libssh2_sftp_closedir(sftp_handle);
227
    libssh2_sftp_shutdown(sftp_session);
228

229
shutdown:
230

231
    if(session) {
232
        libssh2_session_disconnect(session, "Normal Shutdown");
233
        libssh2_session_free(session);
234
    }
235

236
    if(sock != LIBSSH2_INVALID_SOCKET) {
237
        shutdown(sock, 2);
238
        LIBSSH2_SOCKET_CLOSE(sock);
239
    }
240

241
    fprintf(stderr, "all done\n");
242

243
    libssh2_exit();
244

245
#ifdef _WIN32
246
    WSACleanup();
247
#endif
248

249
    return 0;
250
}
251

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

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

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

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