libssh2

Форк
0
/
ssh2_exec.c 
316 строк · 8.4 Кб
1
/* Copyright (C) The libssh2 project and its contributors.
2
 *
3
 * Sample showing how to use libssh2 to execute a command remotely.
4
 *
5
 * The sample code has fixed values for host name, user name, password
6
 * and command to run.
7
 *
8
 * $ ./ssh2_exec 127.0.0.1 user password "uptime"
9
 *
10
 * SPDX-License-Identifier: BSD-3-Clause
11
 */
12

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

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

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

33
static const char *hostname = "127.0.0.1";
34
static const char *commandline = "uptime";
35
static const char *pubkey = "/home/username/.ssh/id_rsa.pub";
36
static const char *privkey = "/home/username/.ssh/id_rsa";
37
static const char *username = "user";
38
static const char *password = "password";
39

40
static int waitsocket(libssh2_socket_t socket_fd, LIBSSH2_SESSION *session)
41
{
42
    struct timeval timeout;
43
    int rc;
44
    fd_set fd;
45
    fd_set *writefd = NULL;
46
    fd_set *readfd = NULL;
47
    int dir;
48

49
    timeout.tv_sec = 10;
50
    timeout.tv_usec = 0;
51

52
    FD_ZERO(&fd);
53

54
#if defined(__GNUC__)
55
#pragma GCC diagnostic push
56
#pragma GCC diagnostic ignored "-Wsign-conversion"
57
#endif
58
    FD_SET(socket_fd, &fd);
59
#if defined(__GNUC__)
60
#pragma GCC diagnostic pop
61
#endif
62

63
    /* now make sure we wait in the correct direction */
64
    dir = libssh2_session_block_directions(session);
65

66
    if(dir & LIBSSH2_SESSION_BLOCK_INBOUND)
67
        readfd = &fd;
68

69
    if(dir & LIBSSH2_SESSION_BLOCK_OUTBOUND)
70
        writefd = &fd;
71

72
    rc = select((int)(socket_fd + 1), readfd, writefd, NULL, &timeout);
73

74
    return rc;
75
}
76

77
int main(int argc, char *argv[])
78
{
79
    uint32_t hostaddr;
80
    libssh2_socket_t sock;
81
    struct sockaddr_in sin;
82
    const char *fingerprint;
83
    int rc;
84
    LIBSSH2_SESSION *session = NULL;
85
    LIBSSH2_CHANNEL *channel;
86
    int exitcode;
87
    char *exitsignal = (char *)"none";
88
    ssize_t bytecount = 0;
89
    size_t len;
90
    LIBSSH2_KNOWNHOSTS *nh;
91
    int type;
92

93
#ifdef _WIN32
94
    WSADATA wsadata;
95

96
    rc = WSAStartup(MAKEWORD(2, 0), &wsadata);
97
    if(rc) {
98
        fprintf(stderr, "WSAStartup failed with error: %d\n", rc);
99
        return 1;
100
    }
101
#endif
102

103
    if(argc > 1) {
104
        hostname = argv[1];  /* must be ip address only */
105
    }
106
    if(argc > 2) {
107
        username = argv[2];
108
    }
109
    if(argc > 3) {
110
        password = argv[3];
111
    }
112
    if(argc > 4) {
113
        commandline = argv[4];
114
    }
115

116
    rc = libssh2_init(0);
117
    if(rc) {
118
        fprintf(stderr, "libssh2 initialization failed (%d)\n", rc);
119
        return 1;
120
    }
121

122
    hostaddr = inet_addr(hostname);
123

124
    /* Ultra basic "connect to port 22 on localhost".  Your code is
125
     * responsible for creating the socket establishing the connection
126
     */
127
    sock = socket(AF_INET, SOCK_STREAM, 0);
128
    if(sock == LIBSSH2_INVALID_SOCKET) {
129
        fprintf(stderr, "failed to create socket.\n");
130
        goto shutdown;
131
    }
132

133
    sin.sin_family = AF_INET;
134
    sin.sin_port = htons(22);
135
    sin.sin_addr.s_addr = hostaddr;
136
    if(connect(sock, (struct sockaddr*)(&sin), sizeof(struct sockaddr_in))) {
137
        fprintf(stderr, "failed to connect.\n");
138
        goto shutdown;
139
    }
140

141
    /* Create a session instance */
142
    session = libssh2_session_init();
143
    if(!session) {
144
        fprintf(stderr, "Could not initialize SSH session.\n");
145
        goto shutdown;
146
    }
147

148
    /* tell libssh2 we want it all done non-blocking */
149
    libssh2_session_set_blocking(session, 0);
150

151
    /* ... start it up. This will trade welcome banners, exchange keys,
152
     * and setup crypto, compression, and MAC layers
153
     */
154
    while((rc = libssh2_session_handshake(session, sock)) ==
155
          LIBSSH2_ERROR_EAGAIN);
156
    if(rc) {
157
        fprintf(stderr, "Failure establishing SSH session: %d\n", rc);
158
        goto shutdown;
159
    }
160

161
    nh = libssh2_knownhost_init(session);
162
    if(!nh) {
163
        /* eeek, do cleanup here */
164
        return 2;
165
    }
166

167
    /* read all hosts from here */
168
    libssh2_knownhost_readfile(nh, "known_hosts",
169
                               LIBSSH2_KNOWNHOST_FILE_OPENSSH);
170

171
    /* store all known hosts to here */
172
    libssh2_knownhost_writefile(nh, "dumpfile",
173
                                LIBSSH2_KNOWNHOST_FILE_OPENSSH);
174

175
    fingerprint = libssh2_session_hostkey(session, &len, &type);
176
    if(fingerprint) {
177
        struct libssh2_knownhost *host;
178
        int check = libssh2_knownhost_checkp(nh, hostname, 22,
179
                                             fingerprint, len,
180
                                             LIBSSH2_KNOWNHOST_TYPE_PLAIN|
181
                                             LIBSSH2_KNOWNHOST_KEYENC_RAW,
182
                                             &host);
183

184
        fprintf(stderr, "Host check: %d, key: %s\n", check,
185
                (check <= LIBSSH2_KNOWNHOST_CHECK_MISMATCH) ?
186
                host->key : "<none>");
187

188
        /*****
189
         * At this point, we could verify that 'check' tells us the key is
190
         * fine or bail out.
191
         *****/
192
    }
193
    else {
194
        /* eeek, do cleanup here */
195
        return 3;
196
    }
197
    libssh2_knownhost_free(nh);
198

199
    if(strlen(password) != 0) {
200
        /* We could authenticate via password */
201
        while((rc = libssh2_userauth_password(session, username, password)) ==
202
              LIBSSH2_ERROR_EAGAIN);
203
        if(rc) {
204
            fprintf(stderr, "Authentication by password failed.\n");
205
            goto shutdown;
206
        }
207
    }
208
    else {
209
        /* Or by public key */
210
        while((rc = libssh2_userauth_publickey_fromfile(session, username,
211
                                                        pubkey, privkey,
212
                                                        password)) ==
213
              LIBSSH2_ERROR_EAGAIN);
214
        if(rc) {
215
            fprintf(stderr, "Authentication by public key failed.\n");
216
            goto shutdown;
217
        }
218
    }
219

220
#if 0
221
    libssh2_trace(session, ~0);
222
#endif
223

224
    /* Exec non-blocking on the remote host */
225
    do {
226
        channel = libssh2_channel_open_session(session);
227
        if(channel ||
228
           libssh2_session_last_error(session, NULL, NULL, 0) !=
229
           LIBSSH2_ERROR_EAGAIN)
230
            break;
231
        waitsocket(sock, session);
232
    } while(1);
233
    if(!channel) {
234
        fprintf(stderr, "Error\n");
235
        exit(1);
236
    }
237
    while((rc = libssh2_channel_exec(channel, commandline)) ==
238
          LIBSSH2_ERROR_EAGAIN) {
239
        waitsocket(sock, session);
240
    }
241
    if(rc) {
242
        fprintf(stderr, "exec error\n");
243
        exit(1);
244
    }
245
    for(;;) {
246
        ssize_t nread;
247
        /* loop until we block */
248
        do {
249
            char buffer[0x4000];
250
            nread = libssh2_channel_read(channel, buffer, sizeof(buffer));
251
            if(nread > 0) {
252
                ssize_t i;
253
                bytecount += nread;
254
                fprintf(stderr, "We read:\n");
255
                for(i = 0; i < nread; ++i)
256
                    fputc(buffer[i], stderr);
257
                fprintf(stderr, "\n");
258
            }
259
            else {
260
                if(nread != LIBSSH2_ERROR_EAGAIN)
261
                    /* no need to output this for the EAGAIN case */
262
                    fprintf(stderr, "libssh2_channel_read returned %ld\n",
263
                            (long)nread);
264
            }
265
        }
266
        while(nread > 0);
267

268
        /* this is due to blocking that would occur otherwise so we loop on
269
           this condition */
270
        if(nread == LIBSSH2_ERROR_EAGAIN) {
271
            waitsocket(sock, session);
272
        }
273
        else
274
            break;
275
    }
276
    exitcode = 127;
277
    while((rc = libssh2_channel_close(channel)) == LIBSSH2_ERROR_EAGAIN)
278
        waitsocket(sock, session);
279

280
    if(rc == 0) {
281
        exitcode = libssh2_channel_get_exit_status(channel);
282
        libssh2_channel_get_exit_signal(channel, &exitsignal,
283
                                        NULL, NULL, NULL, NULL, NULL);
284
    }
285

286
    if(exitsignal)
287
        fprintf(stderr, "\nGot signal: %s\n", exitsignal);
288
    else
289
        fprintf(stderr, "\nEXIT: %d bytecount: %ld\n",
290
                exitcode, (long)bytecount);
291

292
    libssh2_channel_free(channel);
293
    channel = NULL;
294

295
shutdown:
296

297
    if(session) {
298
        libssh2_session_disconnect(session, "Normal Shutdown");
299
        libssh2_session_free(session);
300
    }
301

302
    if(sock != LIBSSH2_INVALID_SOCKET) {
303
        shutdown(sock, 2);
304
        LIBSSH2_SOCKET_CLOSE(sock);
305
    }
306

307
    fprintf(stderr, "all done\n");
308

309
    libssh2_exit();
310

311
#ifdef _WIN32
312
    WSACleanup();
313
#endif
314

315
    return 0;
316
}
317

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

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

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

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