libssh2

Форк
0
/
sftp_write.c 
233 строки · 6.2 Кб
1
/* Copyright (C) The libssh2 project and its contributors.
2
 *
3
 * Sample showing how to do SFTP write transfers.
4
 *
5
 * The sample code has default values for host name, user name, password
6
 * and path to copy, but you can specify them on the command line like:
7
 *
8
 * $ ./sftp_write 192.168.0.1 user password sftp_write.c /tmp/secrets
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
static const char *pubkey = "/home/username/.ssh/id_rsa.pub";
33
static const char *privkey = "/home/username/.ssh/id_rsa";
34
static const char *username = "username";
35
static const char *password = "password";
36
static const char *loclfile = "sftp_write.c";
37
static const char *sftppath = "/tmp/TEST";
38

39
int main(int argc, char *argv[])
40
{
41
    uint32_t hostaddr;
42
    libssh2_socket_t sock;
43
    int i, auth_pw = 1;
44
    struct sockaddr_in sin;
45
    const char *fingerprint;
46
    int rc;
47
    LIBSSH2_SESSION *session = NULL;
48
    LIBSSH2_SFTP *sftp_session;
49
    LIBSSH2_SFTP_HANDLE *sftp_handle;
50
    FILE *local;
51
    char mem[1024 * 100];
52
    size_t nread;
53
    ssize_t nwritten;
54
    char *ptr;
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
        loclfile = argv[4];
80
    }
81
    if(argc > 5) {
82
        sftppath = argv[5];
83
    }
84

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

91
    local = fopen(loclfile, "rb");
92
    if(!local) {
93
        fprintf(stderr, "Cannot open local file %s\n", loclfile);
94
        return 1;
95
    }
96

97
    /*
98
     * The application code is responsible for creating the socket
99
     * and establishing the connection
100
     */
101
    sock = socket(AF_INET, SOCK_STREAM, 0);
102
    if(sock == LIBSSH2_INVALID_SOCKET) {
103
        fprintf(stderr, "failed to create socket.\n");
104
        goto shutdown;
105
    }
106

107
    sin.sin_family = AF_INET;
108
    sin.sin_port = htons(22);
109
    sin.sin_addr.s_addr = hostaddr;
110
    if(connect(sock, (struct sockaddr*)(&sin), sizeof(struct sockaddr_in))) {
111
        fprintf(stderr, "failed to connect.\n");
112
        goto shutdown;
113
    }
114

115
    /* Create a session instance */
116
    session = libssh2_session_init();
117
    if(!session) {
118
        fprintf(stderr, "Could not initialize SSH session.\n");
119
        goto shutdown;
120
    }
121

122
    /* Since we have set non-blocking, tell libssh2 we are blocking */
123
    libssh2_session_set_blocking(session, 1);
124

125
    /* ... start it up. This will trade welcome banners, exchange keys,
126
     * and setup crypto, compression, and MAC layers
127
     */
128
    rc = libssh2_session_handshake(session, sock);
129
    if(rc) {
130
        fprintf(stderr, "Failure establishing SSH session: %d\n", rc);
131
        goto shutdown;
132
    }
133

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

146
    if(auth_pw) {
147
        /* We could authenticate via password */
148
        if(libssh2_userauth_password(session, username, password)) {
149
            fprintf(stderr, "Authentication by password failed.\n");
150
            goto shutdown;
151
        }
152
    }
153
    else {
154
        /* Or by public key */
155
        if(libssh2_userauth_publickey_fromfile(session, username,
156
                                               pubkey, privkey,
157
                                               password)) {
158
            fprintf(stderr, "Authentication by public key failed.\n");
159
            goto shutdown;
160
        }
161
    }
162

163
    fprintf(stderr, "libssh2_sftp_init().\n");
164
    sftp_session = libssh2_sftp_init(session);
165

166
    if(!sftp_session) {
167
        fprintf(stderr, "Unable to init SFTP session\n");
168
        goto shutdown;
169
    }
170

171
    fprintf(stderr, "libssh2_sftp_open().\n");
172
    /* Request a file via SFTP */
173
    sftp_handle = libssh2_sftp_open(sftp_session, sftppath,
174
                                    LIBSSH2_FXF_WRITE |
175
                                    LIBSSH2_FXF_CREAT |
176
                                    LIBSSH2_FXF_TRUNC,
177
                                    LIBSSH2_SFTP_S_IRUSR |
178
                                    LIBSSH2_SFTP_S_IWUSR |
179
                                    LIBSSH2_SFTP_S_IRGRP |
180
                                    LIBSSH2_SFTP_S_IROTH);
181
    if(!sftp_handle) {
182
        fprintf(stderr, "Unable to open file with SFTP: %ld\n",
183
                libssh2_sftp_last_error(sftp_session));
184
        goto shutdown;
185
    }
186

187
    fprintf(stderr, "libssh2_sftp_open() is done, now send data.\n");
188
    do {
189
        nread = fread(mem, 1, sizeof(mem), local);
190
        if(nread <= 0) {
191
            /* end of file */
192
            break;
193
        }
194
        ptr = mem;
195

196
        do {
197
            /* write data in a loop until we block */
198
            nwritten = libssh2_sftp_write(sftp_handle, ptr, nread);
199
            if(nwritten < 0)
200
                break;
201
            ptr += nwritten;
202
            nread -= (size_t)nwritten;
203
        } while(nread);
204
    } while(nwritten > 0);
205

206
    libssh2_sftp_close(sftp_handle);
207
    libssh2_sftp_shutdown(sftp_session);
208

209
shutdown:
210

211
    if(session) {
212
        libssh2_session_disconnect(session, "Normal Shutdown");
213
        libssh2_session_free(session);
214
    }
215

216
    if(sock != LIBSSH2_INVALID_SOCKET) {
217
        shutdown(sock, 2);
218
        LIBSSH2_SOCKET_CLOSE(sock);
219
    }
220

221
    if(local)
222
        fclose(local);
223

224
    fprintf(stderr, "all done\n");
225

226
    libssh2_exit();
227

228
#ifdef _WIN32
229
    WSACleanup();
230
#endif
231

232
    return 0;
233
}
234

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

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

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

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